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 Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Reverse Words in a Given String in Python
Next article icon

Reverse the given string in the range [L, R]

Last Updated : 19 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str, and two integers L and R, the task is to reverse the string in the range [L, R] i.e. str[L…R].
Examples: 

Input: str = “geeksforgeeks”, L = 5, R = 7 
Output: geeksrofgeeks 
Reverse the characters in the range str[5…7] = “geeksforgeeks” 
and the new string will be “geeksrofgeeks”

Input: str = “ijklmn”, L = 1, R = 2 
Output: ikjlmn 

 

Approach:

  1. If the range is invalid i.e. either L < 0 or R ? len or L > R then print the original string.
  2. If the range is valid then keep swapping the characters str[L] and str[R] while L < R and update L = L + 1 and R = R – 1 after every swap operation. Print the updated string in the end.

Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the string after
// reversing characters in the range [L, R]
string reverse(string str, int len, int l, int r)
{
 
    // Invalid range
    if (l < 0 || r >= len || l > r)
        return str;
 
    // While there are characters to swap
    while (l < r) {
 
        // Swap(str[l], str[r])
        char c = str[l];
        str[l] = str[r];
        str[r] = c;
 
        l++;
        r--;
    }
 
    return str;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    int len = str.length();
    int l = 5, r = 7;
 
    cout << reverse(str, len, l, r);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
     
    // Function to return the string after
    // reversing characters in the range [L, R]
    static String reverse(char[] str, int len,
                               int l, int r)
    {
 
        // Invalid range
        if (l < 0 || r >= len || l > r)
            return "Invalid range!";
 
        // While there are characters to swap
        while (l < r)
        {
 
            // Swap(str[l], str[r])
            char c = str[l];
            str[l] = str[r];
            str[r] = c;
 
            l++;
            r--;
        }
        String string = new String(str);
        return string;
    }
 
    // Driver code
    public static void main (String[] args)
    {
        String str = "geeksforgeeks";
        int len = str.length();
        int l = 5, r = 7;
 
        System.out.println(reverse(str.toCharArray(),
                                         len, l, r));
    }
}
 
// This code is contributed by Ashutosh450
 
 

Python3




# Python3 implementation of the approach
 
# Function to return the string after
# reversing characters in the range [L, R]
def reverse(string, length, l, r) :
 
    # Invalid range
    if (l < 0 or r >= length or l > r) :
        return string;
         
    string = list(string)
     
    # While there are characters to swap
    while (l < r) :
 
        # Swap(str[l], str[r])
        c = string[l];
        string[l] = string[r];
        string[r] = c;
 
        l += 1;
        r -= 1;
 
    return "".join(string);
 
# Driver code
if __name__ == "__main__" :
 
    string = "geeksforgeeks";
    length = len(string);
    l = 5; r = 7;
 
    print(reverse(string, length, l, r));
 
# This code is contributed by AnkitRai01
 
 

C#




// C# implementation of the approach
using System;
     
class GFG
{
     
    // Function to return the string after
    // reversing characters in the range [L, R]
    static String reverse(char[] str, int len,
                          int l, int r)
    {
 
        // Invalid range
        if (l < 0 || r >= len || l > r)
            return "Invalid range!";
 
        // While there are characters to swap
        while (l < r)
        {
 
            // Swap(str[l], str[r])
            char c = str[l];
            str[l] = str[r];
            str[r] = c;
 
            l++;
            r--;
        }
        return String.Join("",str);
    }
 
    // Driver code
    public static void Main (String[] args)
    {
        String str = "geeksforgeeks";
        int len = str.Length;
        int l = 5, r = 7;
 
        Console.WriteLine(reverse(str.ToCharArray(),
                                        len, l, r));
    }
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to return the string after
    // reversing characters in the range [L, R]
    function reverse(str, len, l, r)
    {
   
        // Invalid range
        if (l < 0 || r >= len || l > r)
            return "Invalid range!";
   
        // While there are characters to swap
        while (l < r)
        {
   
            // Swap(str[l], str[r])
            let c = str[l];
            str[l] = str[r];
            str[r] = c;
   
            l++;
            r--;
        }
        return str.join("");
    }
     
    let str = "geeksforgeeks";
    let len = str.length;
    let l = 5, r = 7;
 
    document.write(reverse(str.split(''), len, l, r));
 
// This code is contributed by divyeshrabadiya07.
</script>
 
 
Output: 
geeksrofgeeks

 

Time complexity: O(N), where N = (r – l)/2
Auxiliary space: O(1)



Next Article
Reverse Words in a Given String in Python
author
koulick_sadhu
Improve
Article Tags :
  • DSA
  • Strings
  • Reverse
  • substring
Practice Tags :
  • Reverse
  • Strings

Similar Reads

  • Reverse given range of String for M queries
    Given a string S of length N and an array of queries A[] of size M, the task is to find the final string after performing M operations on the string. In each operation reverse a segment of the string S from position (A[i] to N-A[i]+1). Examples: Input: N = 6, S = "abcdef", M = 3, A = {1, 2, 3}Output
    15 min read
  • Program to Reverse the subarray in between given range
    Given an array arr and a range [L, R], the task is to reverse the subarray in between the given range [L, R]. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7], L = 1, R = 5Output: [1, 6, 5, 4, 3, 2, 7] Input: arr = [10, 20, 30, 40, 50], L = 0, R = 2Output: [30, 20, 10, 40, 50] Recommended PracticeRevers
    7 min read
  • Reverse words in a given String in Java
    Let's see an approach to reverse words of a given String in Java without using any of the String library function Examples: Input : "Welcome to geeksforgeeks" Output : "geeksforgeeks to Welcome" Input : "I love Java Programming" Output :"Programming Java love I" Prerequisite: Regular Expression in J
    3 min read
  • Reverse vowels in a given string
    Given a string s, reverse only the vowels in s while keeping the other characters in their original positions. Examples: Input: "geeksforgeeks"Output: "geeksforgeeks"Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks". Input: "helloworld"Output: "hollowerld"Exp
    9 min read
  • Reverse Words in a Given String in Python
    In this article, we explore various ways to reverse the words in a string using Python. From simple built-in methods to advanced techniques like recursion and stacks. We are going to see various techniques to reverse a string. Using split() and join()Using split() and join() is the most common metho
    2 min read
  • Javascript Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "
    4 min read
  • Reverse the string whenever digit is encountered
    Given a string s of length N, the task is to traverse the string and reverse the substring from the start to the next encountered digit. After reversing the substring, update the start index to the character immediately following the digit. Example: Input: s = abc123def456ghiOutput: cba123fed456ihg
    4 min read
  • Reverse all the word in a String represented as a Linked List
    Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence "I love Geeks for Geeks", the Linked List representation is given as: I-> ->l->o->v->e-
    15 min read
  • Print words of a string in reverse order
    Let there be a string say "I AM A GEEK". So, the output should be "GEEK A AM I" . This can done in many ways. One of the solutions is given in Reverse words in a string . Examples: Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG This can be done in more simp
    10 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
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