 Open in App
Not now

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

• Difficulty Level : Hard
• Last Updated : 31 Jan, 2023

Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange characters of the given string such that the same characters become d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should also be reported.
The expected time complexity is O(n + m Log(MAX))  Here n is the length of string, m is the count of distinct characters in a string and MAX is the maximum possible different characters.

Examples:

```Input:  "abb", d = 2
Output: "bab"

Input:  "aacbbc", d = 3
Output: "abcabc"

Input: "geeksforgeeks", d = 3
Output: egkegkesfesor

Input:  "aaa",  d = 2
Output: Cannot be rearranged```

The approach to solving this problem is to count frequencies of all characters and consider the most frequent character first and place all occurrences of it as close as possible. After the most frequent character is placed, repeat the same process for the remaining characters.

1. Let the given string be str and size of string be n
2. Traverse str, store all characters and their frequencies in a Max Heap MH(implemented using priority queue). The value of frequency decides the order in MH, i.e., the most frequent character is at the root of MH.
3. Make all characters of str as ‘\0’.
4. Do the following while MH is not empty.
• Extract the Most frequent character. Let the extracted character be x and its frequency be f.
• Find the first available position in str, i.e., find the first ‘\0’ in str.
• Let the first position be p. Fill x at p, p+d,.. p+(f-1)d

Below is the implementation of the above algorithm.

## C++

 `// C++ program to rearrange a string so that all same``// characters become at least d distance away using STL``#include ``#include ``using` `namespace` `std;``typedef` `pair<``char``, ``int``> PAIR;` `// Comparator of priority_queue``struct` `cmp {``    ``bool` `operator()(``const` `PAIR& a, ``const` `PAIR& b)``    ``{``        ``if``(a.second < b.second) ``return` `true``;``          ``else` `if``(a.second > b.second) ``return` `false``;``          ``else` `return` `a.first > b.first;``    ``}``};` `void` `rearrange(``char``* str, ``int` `d)``{``    ``// Length of the string``    ``int` `n = ``strlen``(str);` `    ``// A structure to store a character and its frequency``    ``unordered_map<``char``, ``int``> m;` `    ``// Traverse the input string and store frequencies of``    ``// all characters.``    ``for` `(``int` `i = 0; i < n; i++) {``        ``m[str[i]]++;``        ``str[i] = ``'\0'``;``    ``}` `    ``// max-heap``    ``priority_queue, cmp> pq(m.begin(),``                                               ``m.end());` `    ``// Now one by one extract all distinct characters from``    ``// heap and put them back in str[] with the d``    ``// distance constraint``    ``while` `(pq.empty() == ``false``) {``        ``char` `x = pq.top().first;``        ` `          ``// Find the first available position in str[]``          ``int` `p = 0;``        ``while` `(str[p] != ``'\0'``)``            ``p++;``          ` `          ``// Fill x at p, p+d, p+2d, .. p+(frequency-1)d``        ``for` `(``int` `k = 0; k < pq.top().second; k++) {``          ` `              ``// If the index goes beyond size, then string``            ``// cannot be rearranged.``            ``if` `(p + d * k >= n) {``                ``cout << ``"Cannot be rearranged"``;``                ``exit``(0);``            ``}``            ``str[p + d * k] = x;``        ``}``        ``pq.pop();``    ``}``}` `// Driver Code``int` `main()``{``    ``char` `str[] = ``"aabbcc"``;``  ` `      ``// Function call``    ``rearrange(str, 3);``    ``cout << str;``}`

## C

 `// C program to rearrange a string so that all same``// characters become at least d distance away``#include ``#include ``#include ``#define MAX 256` `// A structure to store a character 'c' and its frequency``// 'f' in input string``typedef` `struct` `charFreq {``    ``char` `c;``    ``int` `f;``} charFreq ;` `// A utility function to swap two charFreq items.``void` `swap(charFreq* x, charFreq* y)``{``    ``charFreq z = *x;``    ``*x = *y;``    ``*y = z;``}` `// A utility function to maxheapify the node freq[i] of a``// heap stored in freq[]``void` `maxHeapify(charFreq freq[], ``int` `i, ``int` `heap_size)``{``    ``int` `l = i * 2 + 1;``    ``int` `r = i * 2 + 2;``    ``int` `largest = i;``    ``if` `(l < heap_size && freq[l].f > freq[i].f)``        ``largest = l;``    ``if` `(r < heap_size && freq[r].f > freq[largest].f)``        ``largest = r;``    ``if` `(largest != i) {``        ``swap(&freq[i], &freq[largest]);``        ``maxHeapify(freq, largest, heap_size);``    ``}``}` `// A utility function to convert the array freq[] to a max``// heap``void` `buildHeap(charFreq freq[], ``int` `n)``{``    ``int` `i = (n - 1) / 2;``    ``while` `(i >= 0) {``        ``maxHeapify(freq, i, n);``        ``i--;``    ``}``}` `// A utility function to remove the max item or root from``// max heap``charFreq extractMax(charFreq freq[], ``int` `heap_size)``{``    ``charFreq root = freq;``    ``if` `(heap_size > 1) {``        ``freq = freq[heap_size - 1];``        ``maxHeapify(freq, 0, heap_size - 1);``    ``}``    ``return` `root;``}` `// The main function that rearranges input string 'str' such``// that two same characters become d distance away``void` `rearrange(``char` `str[], ``int` `d)``{``    ``// Find length of input string``    ``int` `n = ``strlen``(str);` `    ``// Create an array to store all characters and their``    ``// frequencies in str[]``    ``charFreq freq[MAX] = { { 0, 0 } };` `    ``int` `m = 0; ``// To store count of distinct characters in``               ``// str[]` `    ``// Traverse the input string and store frequencies of``    ``// all characters in freq[] array.``    ``for` `(``int` `i = 0; i < n; i++) {``        ``char` `x = str[i];` `        ``// If this character has occurred first time,``        ``// increment m``        ``if` `(freq[x].c == 0)``            ``freq[x].c = x, m++;` `        ``(freq[x].f)++;``        ``str[i] = ``'\0'``; ``// This change is used later``    ``}` `    ``// Build a max heap of all characters``    ``buildHeap(freq, MAX);` `    ``// Now one by one extract all distinct characters from``    ``// max heap and put them back in str[] with the d``    ``// distance constraint``    ``for` `(``int` `i = 0; i < m; i++) {``        ``charFreq x = extractMax(freq, MAX - i);` `        ``// Find the first available position in str[]``        ``int` `p = i;``        ``while` `(str[p] != ``'\0'``)``            ``p++;` `        ``// Fill x.c at p, p+d, p+2d, .. p+(f-1)d``        ``for` `(``int` `k = 0; k < x.f; k++) {``            ``// If the index goes beyond size, then string``            ``// cannot be rearranged.``            ``if` `(p + d * k >= n) {``                ``printf``(``"Cannot be rearranged"``);``                ``exit``(0);``            ``}``            ``str[p + d * k] = x.c;``        ``}``    ``}``}` `// Driver Code``int` `main()``{``    ``char` `str[] = ``"aabbcc"``;``  ` `      ``// Function Call``    ``rearrange(str, 3);``    ``printf``(``"%s"``,str);``}`

## Java

 `// Java program to rearrange a string so that all same``// characters become at least d distance away``import` `java.util.*;``public` `class` `GFG {` `  ``static` `class` `PAIR ``implements` `Comparable {``    ``char` `first;``    ``int` `second;``    ``PAIR(``char` `f, ``int` `s)``    ``{``      ``first = f;``      ``second = s;``    ``}``    ``public` `int` `compareTo(PAIR b)``    ``{``      ``if` `(``this``.second < b.second)``        ``return` `1``;``      ``else` `if` `(``this``.second > b.second)``        ``return` `-``1``;``      ``else``        ``return` `this``.first - b.first;``    ``}``  ``}` `  ``static` `void` `rearrange(``char``[] str, ``int` `d)``  ``{``    ``// Length of the string``    ``int` `n = str.length;` `    ``// A structure to store a character and its``    ``// frequency``    ``HashMap m = ``new` `HashMap<>();` `    ``// Traverse the input string and store frequencies``    ``// of all characters.``    ``for` `(``int` `i = ``0``; i < n; i++) {``      ``m.put(str[i], m.getOrDefault(str[i], ``0``) + ``1``);``      ``str[i] = ``'\0'``;``    ``}` `    ``// max-heap``    ``PriorityQueue pq = ``new` `PriorityQueue<>();` `    ``for` `(Character key : m.keySet()) {``      ``pq.add(``new` `PAIR(key, m.get(key)));``    ``}``    ``// Now one by one extract all distinct characters``    ``// from heap and put them back in str[] with the d``    ``// distance constraint``    ``while` `(pq.size() != ``0``) {``      ``char` `x = pq.peek().first;` `      ``// Find the first available position in str[]``      ``int` `p = ``0``;``      ``while` `(str[p] != ``'\0'``)``        ``p++;` `      ``// Fill x at p, p+d, p+2d, .. p+(frequency-1)d``      ``for` `(``int` `k = ``0``; k < pq.peek().second; k++) {` `        ``// If the index goes beyond size, then``        ``// string cannot be rearranged.``        ``if` `(p + d * k >= n) {``          ``System.out.println(``            ``"Cannot be rearranged"``);``          ``return``;``        ``}``        ``str[p + d * k] = x;``      ``}``      ``pq.remove();``    ``}``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``char``[] str = ``"aabbcc"``.toCharArray();` `    ``// Function call``    ``rearrange(str, ``3``);``    ``System.out.println(String.valueOf(str));``  ``}``}` `// This code is contributed by Karandeep1234`

## Python3

 `# Python program to rearrange a string so that all same``# characters become at least d distance away``MAX` `=` `256` `# A structure to store a character 'c' and its frequency 'f'``# in input string`  `class` `charFreq(``object``):``    ``def` `__init__(``self``, c, f):``        ``self``.c ``=` `c``        ``self``.f ``=` `f` `# A utility function to swap two charFreq items.`  `def` `swap(x, y):``    ``return` `y, x` `# A utility function`  `def` `toList(string):``    ``t ``=` `[]``    ``for` `x ``in` `string:``        ``t.append(x)` `    ``return` `t` `# A utility function`  `def` `toString(l):``    ``return` `''.join(l)` `# A utility function to maxheapify the node freq[i] of a heap``# stored in freq[]`  `def` `maxHeapify(freq, i, heap_size):``    ``l ``=` `i``*``2` `+` `1``    ``r ``=` `i``*``2` `+` `2``    ``largest ``=` `i``    ``if` `l < heap_size ``and` `freq[l].f > freq[i].f:``        ``largest ``=` `l``    ``if` `r < heap_size ``and` `freq[r].f > freq[largest].f:``        ``largest ``=` `r``    ``if` `largest !``=` `i:``        ``freq[i], freq[largest] ``=` `swap(freq[i], freq[largest])``        ``maxHeapify(freq, largest, heap_size)` `# A utility function to convert the array freq[] to a max heap`  `def` `buildHeap(freq, n):``    ``i ``=` `(n ``-` `1``)``/``/``2``    ``while` `i >``=` `0``:``        ``maxHeapify(freq, i, n)``        ``i ``-``=` `1` `# A utility function to remove the max item or root from max heap`  `def` `extractMax(freq, heap_size):``    ``root ``=` `freq[``0``]``    ``if` `heap_size > ``1``:``        ``freq[``0``] ``=` `freq[heap_size``-``1``]``        ``maxHeapify(freq, ``0``, heap_size``-``1``)` `    ``return` `root` `# The main function that rearranges input string 'str' such that``# two same characters become d distance away`  `def` `rearrange(string, d):``    ``# Find length of input string``    ``n ``=` `len``(string)` `    ``# Create an array to store all characters and their``    ``# frequencies in str[]``    ``freq ``=` `[]``    ``for` `x ``in` `range``(``MAX``):``        ``freq.append(charFreq(``0``, ``0``))` `    ``m ``=` `0` `    ``# Traverse the input string and store frequencies of all``    ``# characters in freq[] array.``    ``for` `i ``in` `range``(n):``        ``x ``=` `ord``(string[i])` `        ``# If this character has occurred first time, increment m``        ``if` `freq[x].c ``=``=` `0``:``            ``freq[x].c ``=` `chr``(x)``            ``m ``+``=` `1` `        ``freq[x].f ``+``=` `1``        ``string[i] ``=` `'\0'` `    ``# Build a max heap of all characters``    ``buildHeap(freq, ``MAX``)` `    ``# Now one by one extract all distinct characters from max heap``    ``# and put them back in str[] with the d distance constraint``    ``for` `i ``in` `range``(m):``        ``x ``=` `extractMax(freq, ``MAX``-``i)` `        ``# Find the first available position in str[]``        ``p ``=` `i``        ``while` `string[p] !``=` `'\0'``:``            ``p ``+``=` `1` `        ``# Fill x.c at p, p+d, p+2d, .. p+(f-1)d``        ``for` `k ``in` `range``(x.f):` `            ``# If the index goes beyond size, then string cannot``            ``# be rearranged.``            ``if` `p ``+` `d``*``k >``=` `n:``                ``print` `(``"Cannot be rearranged"``)``                ``return` `            ``string[p ``+` `d``*``k] ``=` `x.c` `    ``return` `toString(string)`  `# Driver program``string ``=` `"aabbcc"``print` `(rearrange(toList(string), ``3``))` `# This code is contributed by BHAVYA JAIN`

## C#

 `// C# program to rearrange a string so that all same``// characters become at least d distance away using STL``using` `System;``using` `System.Linq;``using` `System.Collections.Generic;` `class` `GFG``{``    ``static` `void` `rearrange(``char``[] str, ``int` `d)``    ``{``        ``// Length of the string``        ``int` `n = str.Length;``    ` `        ``// A structure to store a character and its frequency``        ``Dictionary<``char``, ``int``> m = ``new`  `Dictionary<``char``, ``int``> ();``    ` `        ``// Traverse the input string and store frequencies of``        ``// all characters.``        ``for` `(``int` `i = 0; i < n; i++) {``            ``if` `(!m.ContainsKey(str[i]))``                ``m[str[i]] = 0;``            ``m[str[i]]++;``            ``str[i] = ``'\0'``;``        ``}``    ` `        ``// max-heap``        ``List> pq = ``new` `List>();``        ``foreach` `(``var` `entry ``in` `m)``        ``{``            ``pq.Add(Tuple.Create(entry.Key, entry.Value));``        ``}``        ``pq = pq.OrderBy(a => a.Item2).ThenBy(a => a.Item1).ToList();``        ` `        ``// Now one by one extract all distinct characters from``        ``// heap and put them back in str[] with the d``        ``// distance constraint``        ``while` `(pq.Count > 0) {``            ``char` `x = pq.Item1;``            ` `              ``// Find the first available position in str[]``              ``int` `p = 0;``            ``while` `(str[p] != ``'\0'``)``                ``p++;``              ` `              ``// Fill x at p, p+d, p+2d, .. p+(frequency-1)d``            ``for` `(``int` `k = 0; k < pq.Item2; k++) {``              ` `                  ``// If the index goes beyond size, then string``                ``// cannot be rearranged.``                ``if` `(p + d * k >= n) {``                    ``Console.WriteLine (``"Cannot be rearranged"``);``                    ``return``;``                ``}``                ``str[p + d * k] = x;``            ``}``            ``pq.RemoveAt(0);``        ``}``    ``}``    ` `    ``// Driver Code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``char``[] str = ``"aabbcc"``.ToCharArray();``      ` `          ``// Function call``        ``rearrange(str, 3);``        ``Console.WriteLine(``new` `string``(str));``    ``}``}`

## Javascript

 `// JS program to rearrange a string so that all same``// characters become at least d distance away``let MAX = 256` `const ascii_table = ``"\0\1\2\3\4\5\6\7\8\9\10\11\12\13\14\15\16\17\0\0\20\21\22\23\24\25\26\27\0\0\30\31\32\33\34\35\36\37\0\0\40\41\42\43\44\45\46\47\0\0\50\51\52\53\54\55\56\57\0\0\60\61\62\63\64\65\66\67\0\0\70\71\72\73\74\75\76\77\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\100\101\102\103\104\105\106\107\0\0\110\111\112\113\114\115\116\117\0\0\120\121\122\123\124\125\126\127\0\0\130\131\132\133\134\135\136\137\0\0\140\141\142\143\144\145\146\147\0\0\150\151\152\153\154\155\156\157\0\0\160\161\162\163\164\165\166\167\0\0\170\171\172\173\174\175\176\177\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\200\201\202\203\204\205\206\207\0\0\210\211\212\213\214\215\216\217\0\0\220\221\222\223\224\225\226\227\0\0\230\231\232\233\234\235\236\237\0\0\240\241\242\243\244\245\246\247\0\0\250\251\252\253\254\255"``;` `function` `chr(chr){``  ``return` `ascii_table.indexOf(chr);``}` `function` `ord(index){``  ``return` `ascii_table[index];``}` `// A structure to store a character 'c' and its frequency 'f'``// in input string``class charFreq``{``    ``constructor(c, f)``    ``{``        ``this``.c = c``        ``this``.f = f``    ``}``}` `// A utility function to swap two charFreq items.`  `function` `swap(x, y)``{``    ``return` `[y, x]``}``// A utility function`  `function` `toList(string)``{``    ``let t = []``    ``for` `(let x of string)``        ``t.push(x)` `    ``return` `t``}` `// A utility function`  `function` `toString(l)``{``    ``let res = ``""``    ``for` `(let ele of l)``        ``res += ele``    ``return` `res``}` `// A utility function to maxheapify the node freq[i] of a heap``// stored in freq[]`  `function` `maxHeapify(freq, i, heap_size)``{``    ``let l = i*2 + 1``    ``let r = i*2 + 2``    ``let largest = i``    ``if` `(l < heap_size && freq[l].f > freq[i].f)``        ``largest = l``    ``if` `(r < heap_size && freq[r].f > freq[largest].f)``        ``largest = r``    ``if` `(largest != i)``    ``{``        ``let temp = freq[largest]``        ``freq[largest] = freq[i]``        ``freq[i] = temp``        ``maxHeapify(freq, largest, heap_size)``    ``}``}` `// A utility function to convert the array freq[] to a max heap`  `function` `buildHeap(freq, n)``{``    ``let i = Math.floor((n - 1)/2)``    ``while` `(i >= 0)``    ``{``        ``maxHeapify(freq, i, n)``        ``i -= 1``    ``}``}` `// A utility function to remove the max item or root from max heap`  `function` `extractMax(freq, heap_size)``{``    ``let root = freq``    ``if` `(heap_size > 1)``    ``{``        ``freq = freq[heap_size-1]``        ``maxHeapify(freq, 0, heap_size-1)``    ``}``    ``return` `root``}` `// The main function that rearranges input string 'str' such that``// two same characters become d distance away`  `function` `rearrange(string, d)``{``    ``// Find length of input string``    ``let n = string.length` `    ``// Create an array to store all characters and their``    ``// frequencies in str[]``    ``let freq = []``    ``for` `(``var` `x = 0; x < MAX; x++)``        ``freq.push(``new` `charFreq(0, 0))` `    ``let m = 0`  `    ``// Traverse the input string and store frequencies of all``    ``// characters in freq[] array.``    ``for` `(``var` `i = 0; i < n; i++)``     ``{` `        ``let x = string[i].charCodeAt(0)``        ``// If this character has occurred first time, increment m``        ``if` `(freq[x].c == 0)``        ``{``            ``freq[x].c = String.fromCharCode(x)``            ``m += 1``        ``}``        ` `        ``freq[x].f += 1``        ``string[i] = ``'\0'``    ``}``    ` `    ``// Build a max heap of all characters``    ``buildHeap(freq, MAX)` `    ``// Now one by one extract all distinct characters from max heap``    ``// and put them back in str[] with the d distance constraint``    ``for` `(``var` `i = 0; i < m; i++)``    ``{``        ``x = extractMax(freq, MAX-i)` `        ``// Find the first available position in str[]``        ``let p = i``        ``while` `(string[p] != ``'\0'``)``            ``p += 1` `        ``// Fill x.c at p, p+d, p+2d, .. p+(f-1)d``        ``for` `(``var` `k = 0; k < x.f; k++)``        ``{` `            ``// If the index goes beyond size, then string cannot``            ``// be rearranged.``            ``if` `(p + d*k >= n)``            ``{``                ``console.log (``"Cannot be rearranged"``)``                ``return``            ``}``            ` `            ``string[p + d*k] = x.c``        ``}``    ``}``    ``return` `toString(string)``}`  `// Driver program``let string = ``"aabbcc"``console.log(rearrange(toList(string), 3))`  `// This code is contributed by phasing17`

Output

`abcabc`