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!).

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if all identical characters are at least d positions apart
bool valid(const string &s, int d) {
    for (int i = 0; i < s.length(); i++) {
        for (int j = i + 1; j < s.length(); j++) {
            // Check if characters are the same and too close to each other
            if (s[i] == s[j] && abs(i - j) < d) {
                return false;
            }
        }
    }
    return true;
}

bool rearrange(string s, int d) {
    // Sort the string to start with the lexicographically smallest permutation
    sort(s.begin(), s.end());

    // Try all permutations of the string
    do {
        // For each permutation, check if it satisfies the condition
        if (valid(s, d)) {
            // If valid, print the arrangement and return true
            cout << s << endl;
            return true;
        }
    } while (next_permutation(s.begin(),