Rearrange the given string such that all Prime Multiple indexes have Same Character

A string is a sequence of characters, numbers, Alphanumeric characters and special characters. The length of a string is the number of characters that are present in it. A prime number is the number which is divisible by 1 and the number itself.

In this artice, we are given a sample input string of length n. We are going to develop a code where the idea is to substitute the same character at any position p, such that the the characters at positions ranging from 1 to n/p should coincide.

Some of the examples illustrating the problem statement are as follows −

Sample Example

Example 1 - alphaaa

Output - haaalap

Explanation - The prime indexes 2,4,6 and the indexes 3,6 contain the same character ‘a’.

Example 1 - alphaa

Output - -1

Explanation - As soon as we reduce one character ‘a’ from the string, all the required

positions cannot accommodate the same character. Therefore, the output returned is -1.


  • Step 1 − A map is initialised to keep a count of the characters occurring within the string.

  • Step 2 − A map contains a tuple of the type to store the character and its respective frequency.

  • Step 3 − Every time a character is encountered, its frequency is increased by 1.

  • Step 4 − A vector vec, is also initialized in order to keep map entries in the reversed form, of the nature where the count and the respective character associated with it is pushed into the vector.

  • Step 5 − The vector is then sorted in order to arrange the characters in the order of their frequencies.

  • Step 6 − The position array pos is declared with a size equivalent to maximum value possible.

  • Step 7 − It is initialised with a value 1 using the fill() method available in C++ STL.

  • Step 8 − An iteration of the string is initiated, using the pointer i, beginning with the integer value 2, and if the pos array for this position contains a value, then all the prime multiples using a pointer j, are evaluated.

  • Step 9 − For all the valid positions, the counter of the positions to be filled with the same character is incremented.

  • Step 10 − Otherwise, the pos value of the i*j index is evaluated.

  • Step 11 − The frequency of the most occurring character is then stored, consider it to be much.

  • Step 12 − If the number of positions to be occupied by the same character is greater than the max occurring character frequency, then -1 is returned, since this is an impossible operation.

  • Step 13 − Else, initially all the prime multiple indexes, which are the desirable positions are filled out by the maximum occurring character.

  • Step 14 − The remaining positions are then filled.

  • Step 15 − Every time a character from the vector is taken out and filled at the remaining position.

  • Step 16 − The frequency of this character is decremented.

  • Step 17 − When all the occurrences of a particular character have been exhausted, then next character is fetched from the vector.

  • Step 18 − The final output array string is then printed after swapping the characters.


The following C++ code snippet takes a sample input string and then places the same character on all the prime multiple indices, if possible.

//including the required libraries
#include <bits/stdc++.h>
using namespace std;

//rearranging prime indexes to store same character
void primeindx(string str){

   // To store the result after transformation
   char res[100005];
   int pos[100005];

   //calculating the size of string
   int len = str.size();

   //counter of same elements
   int cnt = 0;

   //maintaining map to store the number of occurrences of characters in string
   map<char, int> map;
   for (auto ch : str){

      //incrementing count of character

   //maintaining a vector to store the different characters in map and their respective counts to sort them according to the frequency
   vector<pair<int, char> > vec;
   for (auto entry : map)
   vec.push_back({ entry.second, entry.first });

   //sorting the vector according to the frequencies
   sort(vec.begin(), vec.end());

   //fill the positions of the array pos with 1
   fill(pos + 1, pos + len + 1, 1);

   //storing indices correctly in the pos array
   for (int i = 2; i <= len / 2; i++) {

      //check if the value at pos[i] is equivalent to 1
      if (pos[i]) {

         //getting all multiples of i
         for (int j = 1; i*j<= len; j++) {
            int val = i*j;
            if (pos[val])

               //incrementing the number of same characters is value is contained in the multiple

            //else storing 0 in the pos vector at that position
            pos[val] = 0;

   //getting the occurrence of the character occurring the maximum number of times
   int mch = vec.back().first;
   if ( mch < cnt) {

      //not possible
      cout << -1;
   for (int i = 2; i <= len; i++) {
      if (!pos[i]) {

         //storing the character at the prime indexes is the count of the same character satisfies
         res[i] = vec.back().second;

   //fetching characters after prime indexes have been filled out
   int k = 0;
   for (int i = 1; i <= len; i++) {

      //if ith index contains 1
      if (pos[i]) {

         //get the character in the result array
         res[i] = vec[k].second;

         //decrement the count available for the character that has been substitutes

         //if there are no more occurrences of that particular character, skip to next one
         if (vec[k].first == 0)

   //printing the final result array
   for(int i =1;i<=len;i++){
      cout << res[i];
//calling the main method
int main(){

   //declaring a sample string
   string str = "codeeee";

   //prime multiple indexes arrangement of character
   return 0;




Character counting is an important aspect of C++ strings. A large number of decisions can be taken based on the frequency of characters available in the string. Maps are an efficient way of storing a data pair, such as characters and their respective counts in a very user-friendly manner.