 GeeksforGeeks App
Open App Browser
Continue

# Reverse substrings of given string according to specified array indices

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: GkeeGrofskees
Explanation:
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: fbdcea
Explanation:
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].
• Print the string after the above steps.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to perform the reversal``// operation on the given string``string 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 Code``int` `main()``{``    ``// Given string str``    ``string str = ``"abcdef"``;` `    ``// Given array of reversing index``    ``int` `arr[] = { 1, 2, 3 };` `    ``int` `K = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// Function Call``    ``cout << modifyString(arr, str, K);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;` `class` `GFG{` `// Function to perform the reversal``// operation on the given String``static` `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 string``static` `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 Code``public` `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

 `# Python3 program for the above approach` `# Function to perform the reversal``# operation on the given string``def` `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 Code``if` `__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#

 `// C# program for the above approach``using` `System;` `class` `GFG{` `// Function to perform the reversal``// operation on the given String``static` `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 string``static` `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 Code``public` `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`

## Javascript

 ``

Output:

`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)

My Personal Notes arrow_drop_up