Reverse substrings of given string according to specified array indices
Last Updated :
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: 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 <iostream>
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[0]);
// 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
<script>
// JavaScript program for the above approach
// Function to perform the reversal
// operation on the given String
function 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 str
let str = "abcdef";
// Given array of reversing index
let arr = [1, 2, 3];
let K = arr.length;
// Function Call
document.write(modifyString(arr, str, K));
// This code is contributed by gfgking
</script>
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)
Similar Reads
Reverse the substrings of the given String according to the given Array of indices Given a string S and an array of indices A[], the task is to reverse the substrings of the given string according to the given Array of indices.Note: A[i] ? length(S), for all i.Examples: Input: S = "abcdef", A[] = {2, 5} Output: baedcf Explanation: Input: S = "abcdefghij", A[] = {2, 5} Output: baed
10 min read
Rearrange a String According to the Given Indices Given a string and a list of indices, the task is to rearrange the characters of the string based on the given indices. For example, if the string is "code" and the indices are [3, 1, 0, 2], the rearranged string should be "edoc". Let's explore various ways in which we can do this in Python.Using li
3 min read
Reverse a string without affecting special characters Given a string, that contains a special character together with alphabets ('a' to 'z' and 'A' to 'Z'), reverse the string in a way that special characters are not affected. Examples: Input: str = "a,b$c"Output: str = "c,b$a"Explanation: Note that $ and , are not moved anywhere. Only subsequence "abc
10 min read
Print all Substrings of length n possible from the given String Given a string str and an integer N, the task is to print all possible sub-strings of length N. Examples: Input: str = âgeeksforgeeksâ, N = 3Output: gee eek eks ksf sfo for org rge gee eek eksExplanations: All possible sub-strings of length 3 are âgeeâ, âeekâ, âeksâ, âksfâ, âsfoâ, âforâ, âorgâ, ârge
8 min read
Find a String in given Array of Strings using Binary Search Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1.Examples:Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index 2.
6 min read
Reverse String according to the number of words Given a string containing a number of words. If the count of words in string is even then reverse its even position's words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order. Examples: Input: Ashish Yadav Abhishek Rajp
6 min read
Find the string among given strings represented using given encryption pattern Given an array of strings arr[] of size N and an encrypted string str, the task is to find the correct string from the given array of strings whose encryption will give str where str is encrypted using the following rules: The starting characters form an integer representing the number of uppercase
8 min read
All substrings of a given String Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string.Examples : Input : s = "abc"Output : "a", "ab", "abc", "b", "bc", "c"Input : s = "ab"Output : "a", "ab", "b"Input : s = "a"Output : "a"[Expected Approach] - Using Iterati
8 min read
Search in an array of strings where non-empty strings are sorted Given an array of strings. The array has both empty and non-empty strings. All non-empty strings are in sorted order. Empty strings can be present anywhere between non-empty strings. Examples: Input : arr[] = {"for", "", "", "", "geeks", "ide", "", "practice", "" , "", "quiz", "", ""}; str = "quiz"
9 min read
Reverse an array in groups of given size | Set 2 (Variations of Set 1 ) Given an array, reverse every sub-array that satisfies the given constraints.We have discussed a solution where we reverse every sub-array formed by consecutive k elements in Set 1. In this set, we will discuss various interesting variations of this problem. Variation 1 (Reverse Alternate Groups): R
15+ min read