- Data Structures & Algorithms
- DSA - Home
- DSA - Overview
- DSA - Environment Setup
- Algorithm
- DSA - Algorithms Basics
- DSA - Asymptotic Analysis
- DSA - Greedy Algorithms
- DSA - Divide and Conquer
- DSA - Dynamic Programming
- Data Structures
- DSA - Data Structure Basics
- DSA - Data Structures and Types
- DSA - Array Data Structure
- Linked Lists
- DSA - Linked List Basics
- DSA - Doubly Linked List
- DSA - Circular Linked List
- Stack & Queue
- DSA - Stack
- DSA - Expression Parsing
- DSA - Queue
- Searching Techniques
- DSA - Linear Search
- DSA - Binary Search
- DSA - Interpolation Search
- DSA - Hash Table
- Sorting Techniques
- DSA - Sorting Algorithms
- DSA - Bubble Sort
- DSA - Insertion Sort
- DSA - Selection Sort
- DSA - Merge Sort
- DSA - Shell Sort
- DSA - Quick Sort
- Graph Data Structure
- DSA - Graph Data Structure
- DSA - Depth First Traversal
- DSA - Breadth First Traversal
- Tree Data Structure
- DSA - Tree Data Structure
- DSA - Tree Traversal
- DSA - Binary Search Tree
- DSA - AVL Tree
- DSA - Red Black Trees
- DSA - B Trees
- DSA - B+ Trees
- DSA - Splay Trees
- DSA - Spanning Tree
- DSA - Tries
- DSA - Heap
- Recursion
- DSA - Recursion Basics
- DSA - Tower of Hanoi
- DSA - Fibonacci Series
- DSA Useful Resources
- DSA - Questions and Answers
- DSA - Quick Guide
- DSA - Useful Resources
- DSA - Discussion

# 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.

## Algorithm

**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 typeto 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 naturewhere 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.

## Example

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 map[ch]+=1; } //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 cnt++; //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; return; } 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 vec[k].first-=1; //if there are no more occurrences of that particular character, skip to next one if (vec[k].first == 0) k++; } } //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 primeindx(str); return 0; }

## Output

ceeedeo

## Conclusion

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.

- Related Articles
- Rearrange string so that same character become n distance apart JavaScript
- Rearrange characters in a string such that no two adjacent are same in C++
- Python program to Rearrange a string so that all same characters become d distance away
- The number 13 and 31 are prime numbers. Both these number have same digit 1 and 3. Find all such pairs of prime numbers up to 100.
- C++ Balanced expressions such that given positions have opening brackets
- Rearrange an array such that arr[i] = i in C++
- Accessing all elements at given Python list of indexes
- How to encode multiple strings that have the same length using Tensorflow and Python?
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string in Python
- Find a string such that every character is lexicographically greater than its immediate next character in Python
- Balanced expressions such that given positions have opening brackets in C++?
- Write the pairs of prime numbers with same digits up to 100, such that 13 and 31.
- The numbers 13 and 31 are prime numbers. Both these numbers have same digits 1 and 3. Find such pairs of prime numbers upto 100 .
- Rearrange array such that even positioned are greater than odd in C++
- C++ program to check we can rearrange array in such a way that given formula returns m or not