Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Rearrange a String According to the Given Indices
Next article icon

Reverse the substrings of the given String according to the given Array of indices

Last Updated : 25 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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: baedcjihgf 

Approach: The idea is to use the concept of reversing the substrings of the given string. 

  • Sort the Array of Indices.
  • Extract the substring formed for each index in the given array as follows: 
    • For the first index in the array A, the substring formed will be from index 0 to A[0] (exclusive) of the given string, i.e. [0, A[0])
    • For all other index in the array A (except for last), the substring formed will be from index A[i] to A[i+1] (exclusive) of the given string, i.e. [A[i], A[i+1])
    • For the last index in the array A, the substring formed will be from index A[i] to L (inclusive) where L is the length of the string, i.e. [A[i], L]
  • Reverse each substring found in the given string

Below is the implementation of the above approach.

C++




// C++ implementation to reverse
// the substrings of the given String
// according to the given Array of indices
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse a string
void reverseStr(string& str,
                int l, int h)
{
    int n = h - l;
 
    // Swap character starting
    // from two corners
    for (int i = 0; i < n / 2; i++) {
        swap(str[i + l], str[n - i - 1 + l]);
    }
}
 
// Function to reverse the string
// with the given array of indices
void reverseString(string& s, int A[], int n)
{
 
    // Reverse the string from 0 to A[0]
    reverseStr(s, 0, A[0]);
 
    // Reverse the string for A[i] to A[i+1]
    for (int i = 1; i < n; i++)
        reverseStr(s, A[i - 1], A[i]);
 
    // Reverse String for A[n-1] to length
    reverseStr(s, A[n - 1], s.length());
}
 
// Driver Code
int main()
{
    string s = "abcdefgh";
    int A[] = { 2, 4, 6 };
    int n = sizeof(A) / sizeof(A[0]);
 
    reverseString(s, A, n);
    cout << s;
 
    return 0;
}
 
 

Java




// Java implementation to reverse
// the subStrings of the given String
// according to the given Array of indices
class GFG
{
 
static String s;
 
// Function to reverse a String
static void reverseStr(int l, int h)
{
    int n = h - l;
 
    // Swap character starting
    // from two corners
    for (int i = 0; i < n / 2; i++)
    {
        s = swap(i + l, n - i - 1 + l);
    }
}
 
// Function to reverse the String
// with the given array of indices
static void reverseString(int A[], int n)
{
 
    // Reverse the String from 0 to A[0]
    reverseStr(0, A[0]);
 
    // Reverse the String for A[i] to A[i+1]
    for (int i = 1; i < n; i++)
        reverseStr(A[i - 1], A[i]);
 
    // Reverse String for A[n-1] to length
    reverseStr(A[n - 1], s.length());
}
static String swap(int i, int j)
{
    char ch[] = s.toCharArray();
    char temp = ch[i];
    ch[i] = ch[j];
    ch[j] = temp;
    return String.valueOf(ch);
}
 
// Driver Code
public static void main(String[] args)
{
    s = "abcdefgh";
    int A[] = { 2, 4, 6 };
    int n = A.length;
 
    reverseString(A, n);
    System.out.print(s);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 implementation to reverse
# the substrings of the given String
# according to the given Array of indices
 
# Function to reverse a string
def reverseStr(str, l, h):
    n = h - l
 
    # Swap character starting
    # from two corners
    for i in range(n//2):
        str[i + l], str[n - i - 1 + l] = str[n - i - 1 + l], str[i + l]
 
# Function to reverse the string
# with the given array of indices
def reverseString(s, A, n):
 
    # Reverse the from 0 to A[0]
    reverseStr(s, 0, A[0])
 
    # Reverse the for A[i] to A[i+1]
    for i in range(1, n):
        reverseStr(s, A[i - 1], A[i])
 
    # Reverse String for A[n-1] to length
    reverseStr(s, A[n - 1], len(s))
 
# Driver Code
s = "abcdefgh"
s = [i for i in s]
A = [2, 4, 6]
n = len(A)
 
reverseString(s, A, n)
print("".join(s))
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# implementation to reverse
// the subStrings of the given String
// according to the given Array of indices
using System;
 
class GFG
{
 
static String s;
 
// Function to reverse a String
static void reverseStr(int l, int h)
{
    int n = h - l;
 
    // Swap character starting
    // from two corners
    for (int i = 0; i < n / 2; i++)
    {
        s = swap(i + l, n - i - 1 + l);
    }
}
 
// Function to reverse the String
// with the given array of indices
static void reverseString(int []A, int n)
{
 
    // Reverse the String from 0 to A[0]
    reverseStr(0, A[0]);
 
    // Reverse the String for A[i] to A[i+1]
    for (int i = 1; i < n; i++)
        reverseStr(A[i - 1], A[i]);
 
    // Reverse String for A[n-1] to length
    reverseStr(A[n - 1], s.Length);
}
 
static String swap(int i, int j)
{
    char []ch = s.ToCharArray();
    char temp = ch[i];
    ch[i] = ch[j];
    ch[j] = temp;
    return String.Join("",ch);
}
 
// Driver Code
public static void Main(String[] args)
{
    s = "abcdefgh";
    int []A = { 2, 4, 6 };
    int n = A.Length;
 
    reverseString(A, n);
    Console.Write(s);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript implementation to reverse
// the substrings of the given String
// according to the given Array of indices
 
// Function to reverse a string
function reverseStr(str, l, h)
{
    var n = h - l;
 
    // Swap character starting
    // from two corners
    for (var i = 0; i < n / 2; i++) {
        [str[i + l], str[n - i - 1 + l]] =
        [str[n - i - 1 + l], str[i + l]];
    }
    return str;
}
 
// Function to reverse the string
// with the given array of indices
function reverseString(s, A, n)
{
 
    // Reverse the string from 0 to A[0]
    s = reverseStr(s, 0, A[0]);
 
    // Reverse the string for A[i] to A[i+1]
    for (var i = 1; i < n; i++)
        s = reverseStr(s, A[i - 1], A[i]);
 
    // Reverse String for A[n-1] to length
    s = reverseStr(s, A[n - 1], s.length);
    return s;
}
 
// Driver Code
var s = "abcdefgh";
var A = [2, 4, 6];
var n = A.length;
s = reverseString(s.split(''), A, n);
document.write( s.join(''));
 
</script>
 
 
Output: 
badcfehg

 

Time Complexity: O(l * n), where l is the length of the given string and n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Approach:

The task of the reverse_substring() function is to reverse the substrings of a given string s at the indices specified in the list A. Here’s how the algorithm works:

  1. Convert the string s into a list of characters so that it can be modified in-place.
  2. Add 0 and the length of the string s as the first and last elements to the list A respectively, to account for the reversal of the substrings at the beginning and end of the string.
  3. Loop through the indices in the list A starting from the second index (since we’ve already added the first index).
  4. For each index, determine the start and end indices of the substring to be reversed by subtracting the previous and current index values in A respectively. For example, if A is [2, 4, 6], and the current index is 1, then the start and end indices are 0 and 1 respectively, since 2-0=2 and 4-0=4, and we need to reverse the substring starting at index 0 and ending at index 1.
  5. Reverse the substring between the start and end indices using a two-pointer approach. This is done by swapping the characters at the start and end indices, and then incrementing the start index and decrementing the end index until they meet in the middle.
  6. Join the characters in the modified list back into a string and return it.

Below is the implementation of the above approach.

C++




#include <iostream>
#include <vector>
using namespace std;
 
string reverseSubstring(string s, vector<int> A) {
    A.insert(A.begin(), 0);
    A.push_back(s.length());
    for (int i = 1; i < A.size(); i++) {
        int l = A[i-1], r = A[i]-1;
        while (l < r) {
            swap(s[l], s[r]);
            l++;
            r--;
        }
    }
    return s;
}
 
// Driver code
int main() {
    string s = "abcdefgh";
    vector<int> A = {2, 4, 6};
    cout << reverseSubstring(s, A);
    return 0;
}
 
 

Java




import java.util.*;
 
public class Main {
    public static String reverseSubstring(String s, List<Integer> A) {
        List<Integer> indices = new ArrayList<>(A);
        indices.add(0, 0);
        indices.add(s.length());
        char[] chars = s.toCharArray();
        for (int i = 1; i < indices.size(); i++) {
            int l = indices.get(i-1), r = indices.get(i)-1;
            while (l < r) {
                char temp = chars[l];
                chars[l] = chars[r];
                chars[r] = temp;
                l++;
                r--;
            }
        }
        return new String(chars);
    }
 
    // Driver code
    public static void main(String[] args) {
        String s = "abcdefgh";
        List<Integer> A = Arrays.asList(2, 4, 6);
        System.out.println(reverseSubstring(s, A));  // Output: "abfedchhg"
    }
}
 
 

Python3




def reverse_substring(s, A):
    s = list(s)
    A = [0] + A + [len(s)]
    for i in range(1, len(A)):
        l, r = A[i-1], A[i]-1
        while l < r:
            s[l], s[r] = s[r], s[l]
            l += 1
            r -= 1
    return ''.join(s)
 
# Driver code
s = "abcdefgh"
A = [2, 4, 6]
print(reverse_substring(s, A))
 
 

C#




//GFG
//C# implementation of the given approach
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Program
{
    public static string ReverseSubstring(string s, List<int> A)
    {
        List<int> indices = new List<int>(A);
        indices.Insert(0, 0);
        indices.Add(s.Length);
        char[] chars = s.ToCharArray();
        for (int i = 1; i < indices.Count; i++)
        {
            int l = indices[i - 1], r = indices[i] - 1;
            while (l < r)
            {
                char temp = chars[l];
                chars[l] = chars[r];
                chars[r] = temp;
                l++;
                r--;
            }
        }
        return new string(chars);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string s = "abcdefgh";
        List<int> A = new List<int> { 2, 4, 6 };
        Console.WriteLine(ReverseSubstring(s, A)); // Output: "abfedchhg"
    }
}
 
//This code is written by Sundaram
 
 

Javascript




function reverseSubstring(s, A) {
    A.unshift(0);
    A.push(s.length);
    let chars = s.split("");
    for (let i = 1; i < A.length; i++) {
        let l = A[i-1], r = A[i]-1;
        while (l < r) {
            [chars[l], chars[r]] = [chars[r], chars[l]];
            l++;
            r--;
        }
    }
    return chars.join("");
}
 
// Driver code
let s = "abcdefgh";
let A = [2, 4, 6];
console.log(reverseSubstring(s, A));  // Output: "abfedchhg"
 
 
Output
badcfehg

The time complexity of this algorithm is O(n), where n is the length of the string s, since we loop through the indices in list A and reverse the substrings in place. 
The Auxiliary space is also O(n) since we convert the string s into a list of characters.



Next Article
Rearrange a String According to the Given Indices

S

Sanjit_Prasad
Improve
Article Tags :
  • Arrays
  • DSA
  • Pattern Searching
  • Strings
  • substring
Practice Tags :
  • Arrays
  • Pattern Searching
  • Strings

Similar Reads

  • 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: GkeeGrofskeesExplanatio
    7 min read
  • Print all strings in the given array that occur as the substring in the given string
    Given an array of string arr[] and a string str, the task is to print all the strings in arr[] that occur as a substring in str. Example: Input: str ="geeksforgeeks", arr[] ={ "forg", "geek", "ek", "dog", "sfor"}Output: forggeekeksforExplanation: The strings "forg", "geek", "ek" and "sfor" occur as
    5 min read
  • Number of ways to form a given String from the given set of Strings
    Given a string str and an array of strings dictionary[], the task is to find the number of ways str can be formed as a concatenation of strings (any number of times) in a dictionary[]. Examples: Input: str = abab, dictionary[] = { a, b, ab }Output: 4Explanation: There are 4 ways to form string str a
    15+ 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 l
    3 min read
  • Sort the Array of Strings on the basis of given substring range
    Given two positive integers I and X and an array of strings arr[], the task is to sort the given array of strings on the basis of substrings starting from index I of size X. Examples: Input: I = 2, X = 2, arr[] = { "baqwer", "zacaeaz", "aaqzzaa", "aacaap", "abbatyo", "bbbacztr", "bbbdaaa" } Output:
    6 min read
  • Count of Reverse Bitonic Substrings in a given String
    Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasin
    8 min read
  • Find the Longest Non-Prefix-Suffix Substring in the Given String
    Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix
    7 min read
  • Check if the string has a reversible equal substring at the ends
    Given a string S consisting of N characters, the task is to check if this string has a reversible equal substring from the start and the end. If yes, print True and then the longest substring present following the given conditions, otherwise print False. Example: Input: S = "abca"Output: TrueaExplan
    5 min read
  • Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
    Given a string str, its sub-strings are formed in such a way that all the sub-strings starting with the first character of the string will occur first in the sorted order of their lengths followed by all the sub-strings starting with the second character of the string in the sorted order of their le
    9 min read
  • Find the longest Substring of a given String S
    Given a string S of length, N. Find the maximum length of any substring of S such that, the bitwise OR of all the characters of the substring is equal to the bitwise OR of the remaining characters of the string. If no such substring exists, print -1. Examples: Input: S = "2347"Output: 3?Explanation:
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences