VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

⇱ Rearrange a string so that all same characters become d distance away - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange a string so that all same characters become d distance away

Last Updated : 23 Jul, 2025

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.

[Naive Approach] Checking all permutations - O(n! * n^2) time and O(n) space

The idea is to generate all permutations of the string and checks each one to see if identical characters are at least d positions apart. It guarantees finding a solution if it exists but is inefficient due to the factorial growth of permutations (n!).


Output
abcabc

Time Complexity: O(n! * n2), n! for generating all permutations
Auxiliary space : O(n)

[Expected Approach] Using Max Heap - O(n + m * log m) time and O(n) space

The idea is to use a greedy algorithm to place the most frequent characters first, ensuring identical characters are at least d positions apart. A max heap selects the frequent characters, and the string is filled by placing characters at intervals of d, 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.


Output
abcabc

Time Complexity: (n + m * log m), m is maximum number of distinct character in string
Auxiliary space : O(n)

Comment
Article Tags:
Article Tags: