Reverse substrings of given string according to specified array indices - GeeksforGeeks

18 Jun, 2021
Given string str of length N and an array arr[] of integers, for array element arr[i](1-based indexing), reverse the substring in indices [arr[i], N – arr[i] + 1]. The task is to print the string after every reversal.
Examples:
Input: str = “GeeksforGeeks”, arr[] = {2}Output: GkeeGrofskeesExplanation:For first element of the array is 2:Reverse the substring (2, 12). Now the updated string is “GkeeGrofskees”.
Input: str = “abcdef”, arr[] = {1, 2, 3}Output: fbdceaExplanation:For first element of the array is 1:Reverse the substring (1, 6). Now the updated string is “fedcba”.For second element of the array is 2:Reverse the substring (2, 5). Now the updated string is “fbcdea”.For third element of the array is 3:Reverse the substring (3, 4). Now the updated string is “fbdcea”.
Naive Approach: The simplest approach is to traverse the given array and for each array element arr[i] reverse the substring {s[arr[i]], ... s[N – arr[i] + 1]} and print the resultant string obtained after very update. 
Time Complexity: O(N * K), where N is the length of the string and K is the maximum length of the substring reversed.Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by keeping the track of the number of times any character at an index has been reversed. If the count of reversal is even, then the character will come back to its original place, so there will be no change and if the count of reversal is odd, then the character has to be swapped. Below are the steps:
Initialize an array count[] to store the number of reversals at any index of the string.
Traverse the given array arr[] and increment the count of indices count[arr[i]] by 1.
Now, traverse the array count[] over the range [1, N/2] using the variable i and do the following:Update the element at the current index as the sum of the current and previous index.Now, if current element count[i] is odd, then swap str[i] and str[N – i + 1].
Update the element at the current index as the sum of the current and previous index.
Now, if current element count[i] is odd, then swap str[i] and str[N – i + 1].
Print the string after the above steps.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <iostream>using namespace std; // Function to perform the reversal// operation on the given stringstring modifyString(int A[], string str,                    int K){    // Size of string    int N = str.size();     // Stores the count of indices    int count[N + 1] = { 0 };     // Count the positions where    // reversals will begin    for (int i = 0; i < K; i++) {        count[A[i]]++;    }     for (int i = 1; i <= N / 2; i++) {         // Store the count of reversals        // beginning at position i        count[i] = count[i] + count[i - 1];         // Check if the count[i] is        // odd the swap the character        if (count[i] & 1) {            swap(str[i - 1], str[N - i]);        }    }     // Return the updated string    return str;} // Driver Codeint main(){    // Given string str    string str = "abcdef";     // Given array of reversing index    int arr[] = { 1, 2, 3 };     int K = sizeof(arr) / sizeof(arr[0]);     // Function Call    cout << modifyString(arr, str, K);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to perform the reversal// operation on the given Stringstatic String modifyString(int A[], String str,                           int K){         // Size of String    int N = str.length();     // Stores the count of indices    int count[] = new int[N + 1];     // Count the positions where    // reversals will begin    for(int i = 0; i < K; i++)    {        count[A[i]]++;    }     for(int i = 1; i <= N / 2; i++)    {                 // Store the count of reversals        // beginning at position i        count[i] = count[i] + count[i - 1];         // Check if the count[i] is        // odd the swap the character        if ((count[i] & 1) > 0)        {            str = swap(str, i - 1, N - i);        }    }     // Return the updated String    return str;} // Swap char of a stringstatic String swap(String str, int i, int j){    char ch[] = str.toCharArray();    char temp = ch[i];    ch[i] = ch[j];    ch[j] = temp;    return String.valueOf(ch);} // Driver Codepublic static void main(String[] args){         // Given String str    String str = "abcdef";     // Given array of reversing index    int arr[] = { 1, 2, 3 };     int K = arr.length;     // Function Call    System.out.print(modifyString(arr, str, K));}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to perform the reversal# operation on the given stringdef modifyString(A, str, K):         # Size of string    N = len(str)     # Stores the count of indices    count = [0] * (N + 1)     # Count the positions where    # reversals will begin    for i in range(K):        count[A[i]] += 1     for i in range(1, N // 2 + 1):                 # Store the count of reversals        # beginning at position i        count[i] = count[i] + count[i - 1]         # Check if the count[i] is        # odd the swap the character        if (count[i] & 1):            str[i - 1], str[N - i] = str[N - i], str[i - 1]     # Return the updated string    return "".join(str) # Driver Codeif __name__ == '__main__':         # Given str    str1 = "abcdef"    str = [i for i in str1]     # Given array of reversing index    arr = [ 1, 2, 3 ]     K = len(arr)         # Function Call    print(modifyString(arr, str, K)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{ // Function to perform the reversal// operation on the given Stringstatic String modifyString(int []A, String str,                           int K){         // Size of String    int N = str.Length;     // Stores the count of indices    int []count = new int[N + 1];     // Count the positions where    // reversals will begin    for(int i = 0; i < K; i++)    {        count[A[i]]++;    }     for(int i = 1; i <= N / 2; i++)    {                 // Store the count of reversals        // beginning at position i        count[i] = count[i] + count[i - 1];         // Check if the count[i] is        // odd the swap the character        if ((count[i] & 1) > 0)        {            str = swap(str, i - 1, N - i);        }    }     // Return the updated String    return str;} // Swap char of a stringstatic String swap(String str, int i, int j){    char []ch = str.ToCharArray();    char temp = ch[i];    ch[i] = ch[j];    ch[j] = temp;     return String.Join("", ch);} // Driver Codepublic static void Main(String[] args){         // Given String str    String str = "abcdef";     // Given array of reversing index    int []arr = { 1, 2, 3 };     int K = arr.Length;     // Function Call    Console.Write(modifyString(arr, str, K));}} // This code is contributed by Amit Katiyar
<script> // JavaScript program for the above approach  // Function to perform the reversal// operation on the given Stringfunction modifyString(A, str, K) {     // Size of String    str = str.split("")    let N = str.length;     // Stores the count of indices    let count = new Array(N + 1).fill(0);     // Count the positions where    // reversals will begin    for (let i = 0; i < K; i++) {        count[A[i]] += 1;    }     for (let i = 1; i <= N / 2; i++) {         // Store the count of reversals        // beginning at position i        count[i] = count[i] + count[i - 1];         // Check if the count[i] is        // odd the swap the character        if (count[i] & 1) {            let temp = str[i - 1];            str[i - 1] = str[N - i];            str[N - i] = temp        }    }     // Return the updated String    return str.join("");}   // Driver Code // Given String strlet str = "abcdef"; // Given array of reversing indexlet arr = [1, 2, 3]; let K = arr.length; // Function Calldocument.write(modifyString(arr, str, K)); // This code is contributed by gfgking </script>
fbdcea
 
Time Complexity: O(N + K), where N is the length of the string and K is the maximum length of the substring reversed. Auxiliary Space: O(N)
mohit kumar 29
amit143katiyar
gfgking
frequency-counting
Hash
Hash
Mathematical
Strings
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rearrange an array such that arr[i] = i
Design a data structure that supports insert, delete, search and getRandom in constant time
Quadratic Probing in Hashing
Hashing in Java
What are Hash Functions and How to choose a good Hash Function?
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7