VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-the-given-string-in-the-range-l-r/

⇱ Reverse the given string in the range [L, R] - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 19 Oct, 2022

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:


Output: 
geeksrofgeeks

 

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

Comment
Article Tags: