![]() |
VOOZH | about |
Given a string s and a positive integer d, rearrange the characters of the string so that any two identical characters are at least d positions apart. If no such arrangement is possible, print "Cannot be rearranged".
Examples:
Input: s="abb", d = 2
Output: "bab"
Explanation: The character 'a' and 'b' need to be rearranged such that 'b' appears at least 2 positions away from the other 'b'. One valid solution is "bab", where the two 'b's are at positions 2 and 3, satisfying the distance requirement.Input: s="aacbbc", d = 3
Output: "abcabc"
Explanation: The characters are rearranged so that each pair of identical characters ('a', 'b', 'c') are placed at least 3 positions apart. One valid solution is "abcabc".Input: s="geeksforgeeks", d = 3
Output: "egkegkesfesor"
Explanation: The characters are rearranged such that identical characters are at least 3 positions apart. One valid solution is "egkegkesfesor".Input: s="aaa", d = 2
Output: "Cannot be rearranged"
Explanation: It's impossible to rearrange the characters of the string such that 'a' appears more than once and still respects the required distance of 2.
Table of Content
The idea is to generate all permutations of the string and checks each one to see if identical characters are at least
dpositions apart. It guarantees finding a solution if it exists but is inefficient due to the factorial growth of permutations (n!).
abcabc
Time Complexity: O(n! * n2), n! for generating all permutations
Auxiliary space : O(n)
The idea is to use a greedy algorithm to place the most frequent characters first, ensuring identical characters are at least
dpositions apart. A max heap selects the frequent characters, and the string is filled by placing characters at intervals ofd, maintaining the required distance. At any point, if we are not able to place, we return. At the end, if we are able to place all, we return the result string.
abcabc
Time Complexity: (n + m * log m), m is maximum number of distinct character in string
Auxiliary space : O(n)