C++ program to Reorder the Given String to Form a K-Concatenated String


We are given a string and an integer k, and we need to reorder the characters in the string so that it becomes the concatenation of k similar substring. If not possible, output the result as "Impossible”.

string = "malaalam";
K = 2;
res = solve(s, K);

Example (Using Maps)

Let's have a string "mottom" and K=2. The given string can be represented as the concatenation of 2 substrings like tomtom, motmot omtomt, etc. As in all 3, two substrings are joined together when k = 2.

Using the string, we can determine how many times each character occurs. After that, if all the available frequencies are divisible by k, then it is possible, and we can output any possible answer. Otherwise, it is not possible.

The C++ implementation of the above example is as follows −

#include <iostream> #include <map> using namespace std; string solve(string s, int k) { map<char, int> mp; for (char ch : s) { mp[ch]++; } string repeatedSubstring = ""; for (auto &val : mp) { if ((val.second % k) != 0) { return "Impossible"; } else { for (int i=0;i<val.second/k;i++) { repeatedSubstring+=val.first; } } } string ans = ""; for (int i = 0; i < k; i++) { ans+= repeatedSubstring; } return ans; } int main() { string s = "mottom"; int K = 2; cout << solve(s, K); return 0; }

Output

motmot

Example (Without Using Maps)

The C++ implementation of the same example, without using maps is as follows −

#include <bits/stdc++.h> using namespace std; int main() { string str = "mottom"; int k = 2; int frqncy[26] = { 0 }; int len = str.length(); for (int i = 0; i < len; i++) { frqncy[str[i] - 'a']++; } string single_copy = ""; for (int i = 0; i < 26; i++) { if (frqncy[i] != 0) { if ((frqncy[i] % k) != 0) { string ans = "Not Possible"; cout << ans; } else { int total_occurrences = (frqncy[i] / k); for (int j = 0; j < total_occurrences; j++) { single_copy += char(i + 97); } } } } string kString; for (int i = 0; i < k; i++) { kString += single_copy; } cout << kString; return 0; }

Output

motmot

Conclusion

We can use a map or unordered_map to hash the character to frequency. We can use an array of [26] for Latin lower case characters and set all freq to 0. This is an implementation-based problem with O(n) time complexity with unordered_map or hashmap.

Updated on: 10-Aug-2022

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements