Modify a string by circularly shifting each character to the right by respective frequencies - GeeksforGeeks

28 May, 2021
Given a string S consisting of lowercase English alphabets, the task is to right shift each character of the given string S circularly by its frequency.
Circular shifting of characters refers to shifting character ‘z’ to ‘a’, as its next character.
Examples:
Input: S = “geeksforgeeks”Output: iiimugpsiiimu Explanation:Following changes are made on the string S:
Frequency of ‘g’ is 2. Therefore, shifting the character ‘g’ by 2 becomes ‘i’.Frequency of ‘e’ is 4. Therefore, shifting the character ‘e’ by 4 becomes ‘i’.Frequency of ‘k’ is 2. Therefore, shifting the character ‘k’ by 2 becomes ‘m’.Frequency of ‘s’ is 2. Therefore, shifting the character ‘s’ by 2 becomes ‘u’.Frequency of ‘f’ is 1. Therefore, shifting the character ‘f’ by 1 becomes ‘g’.Frequency of ‘o’ is 1. Therefore, shifting the character ‘o’ by 1 becomes ‘p’.Frequency of ‘r’ is 1. Therefore, shifting the character ‘r’ by 1 becomes ‘s’.
Frequency of ‘g’ is 2. Therefore, shifting the character ‘g’ by 2 becomes ‘i’.
Frequency of ‘e’ is 4. Therefore, shifting the character ‘e’ by 4 becomes ‘i’.
Frequency of ‘k’ is 2. Therefore, shifting the character ‘k’ by 2 becomes ‘m’.
Frequency of ‘s’ is 2. Therefore, shifting the character ‘s’ by 2 becomes ‘u’.
Frequency of ‘f’ is 1. Therefore, shifting the character ‘f’ by 1 becomes ‘g’.
Frequency of ‘o’ is 1. Therefore, shifting the character ‘o’ by 1 becomes ‘p’.
Frequency of ‘r’ is 1. Therefore, shifting the character ‘r’ by 1 becomes ‘s’.
After the above shifting of characters, the string modifies to “iiimugpsiiimu”.
Input: S = “aabcadb”Output: ddddded
Approach: The idea to solve this problem is to traverse the string and find the frequency of occurrence of each character in the string and then increment each of the characters by its frequency. Follow the steps below to solve the problem:
Initialize an array, say frequency[] that stores the occurrences of each character in the string S.
Traverse the given string S and perform the following steps:Find the frequency of the current character S[i].Increment the current character by its frequency and update the value of S[i] to its updated character.
Find the frequency of the current character S[i].
Increment the current character by its frequency and update the value of S[i] to its updated character.
After completing the above steps, print the string S as the resultant modified string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to replace the characters// by its frequency of character in itvoid addFrequencyToCharacter(string S){    // Stores frequencies of characters    // in the string S    int frequency[26] = { 0 };     int N = S.length();     // Traverse the string S    for (int i = 0; i < N; i++) {         // Increment the frequency of        // each character by 1        frequency[S[i] - 'a'] += 1;    }     // Traverse the string S    for (int i = 0; i < N; i++) {         // Find the frequency of        // the current character        int add = frequency[S[i] - 'a'] % 26;         // Update the character        if (int(S[i]) + add            <= int('z'))            S[i] = char(int(S[i])                        + add);         else {            add = (int(S[i]) + add)                  - (int('z'));            S[i] = char(int('a')                        + add - 1);        }    }     // Print the resultant string    cout << S;} // Driver Codeint main(){    string S = "geeksforgeeks";    addFrequencyToCharacter(S);     return 0;}
// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG {     // Function to replace the characters    // by its frequency of character in it    static void addFrequencyToCharacter(String Str)    {        // Stores frequencies of characters        // in the string S        int frequency[] = new int[26];         int N = Str.length();        char S[] = Str.toCharArray();         // Traverse the string S        for (int i = 0; i < N; i++) {             // Increment the frequency of            // each character by 1            frequency[S[i] - 'a'] += 1;        }         // Traverse the string S        for (int i = 0; i < N; i++) {             // Find the frequency of            // the current character            int add = frequency[S[i] - 'a'] % 26;             // Update the character            if ((int)(S[i]) + add <= (int)('z'))                S[i] = (char)((int)(S[i]) + add);             else {                add = ((int)(S[i]) + add) - ((int)('z'));                S[i] = (char)((int)('a') + add - 1);            }        }         // Print the resultant string        System.out.println(new String(S));    }     // Driver Code    public static void main(String[] args)    {        String S = "geeksforgeeks";        addFrequencyToCharacter(S);    }} // This code is contributed by Kingash.
# Python3 program for the above approach # Function to replace the characters# by its frequency of character in itdef addFrequencyToCharacter(S):     # Stores frequencies of characters    # in the string S    frequency = [0 for i in range(26)]     N = len(S)         S = list(S)    # Traverse the string S    for i in range(N):         # Increment the frequency of        # each character by 1        frequency[ord(S[i]) - ord('a')] += 1         # Traverse the string S    for i in range(N):         # Find the frequency of        # the current character        add = frequency[ord(S[i]) - ord('a')] % 26         # Update the character        if ord(S[i]) + add <= ord('z'):            S[i] = chr(ord(S[i]) + add)         else:            add = ord(S[i]) + add - ord('z')            S[i] = chr(ord('a') + add - 1)         # Print the resultant string    s = ""    print(s.join(S)) # Driver Codeif __name__ == '__main__':         S = "geeksforgeeks"         addFrequencyToCharacter(S)     # This code is contributed by jana_sayantan
// C# program for the above approachusing System;class GFG{ // Function to replace the characters// by its frequency of character in itstatic void addFrequencyToCharacter(string Str){         // Stores frequencies of characters    // in the string S    int[] frequency = new int[26];     int N = Str.Length;    char[] S = Str.ToCharArray();     // Traverse the string S    for(int i = 0; i < N; i++)    {                 // Increment the frequency of        // each character by 1        frequency[S[i] - 'a'] += 1;    }     // Traverse the string S    for(int i = 0; i < N; i++)    {                 // Find the frequency of        // the current character        int add = frequency[S[i] - 'a'] % 26;         // Update the character        if ((int)(S[i]) + add <= (int)('z'))            S[i] = (char)((int)(S[i]) + add);         else        {            add = ((int)(S[i]) + add) - ((int)('z'));            S[i] = (char)((int)('a') + add - 1);        }    }     // Print the resultant string    Console.Write(new string(S));} // Driver Codepublic static void Main(string[] args){    string S = "geeksforgeeks";    addFrequencyToCharacter(S);}} // This code is contributed by ukasp
<script> // Javascript program for the above approach  // Function to replace the characters// by its frequency of character in itfunction addFrequencyToCharacter(Str){    // Stores frequencies of characters    // in the string S    var frequency = Array.from({length: 26}, (_, i) => 0);     var N = Str.length;    var S = Str.split('');     // Traverse the string S    for (var i = 0; i < N; i++) {         // Increment the frequency of        // each character by 1        frequency[S[i].charCodeAt(0) -        'a'.charCodeAt(0)] += 1;    }     // Traverse the string S    for (var i = 0; i < N; i++) {         // Find the frequency of        // the current character        var add = frequency[S[i].charCodeAt(0) -        'a'.charCodeAt(0)] % 26;         // Update the character        if ((S[i].charCodeAt(0)) +                               add <= ('z').charCodeAt(0))            S[i] = String.fromCharCode((S[i].charCodeAt(0))            + add);         else {            add = ((S[i].charCodeAt(0)) + add) -            (('z').charCodeAt(0));            S[i] = String.fromCharCode(('a'.charCodeAt(0)) +            add - 1);        }    }     // Print the resultant string    document.write(S.join(''));} // Driver Codevar S = "geeksforgeeks";addFrequencyToCharacter(S); // This code contributed by shikhasingrajput </script>
iiimugpsiiimu
 
Time Complexity: O(N)Auxiliary Space: O(26)
Kingash
ukasp
shikhasingrajput
jana_sayantan
frequency-counting
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not