VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-string-without-using-any-temporary-variable/

⇱ Reverse string without using any temporary variable - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse string without using any temporary variable

Last Updated : 23 Jul, 2025

We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable.

Examples: 

Input : str = "abc"
Output : str = "cba" 

Input : str = "GeeksforGeeks"
Output : str = "skeeGrofskeeG"

If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable. Below is the implementation of the idea.  

Output: 

skeeGrofskeeG

Time Complexity: O(n) 
Auxiliary Space: O(1)


If we are allowed to library function, we can also use the idea discussed in quickly reverse a string in C++. We don't even need indexes of first and last characters. 

Output: 

skeegrofskeeg

Time complexity : O(n) 
Auxiliary Space : O(1)


This article is contributed by Aarti_Rathi and Mr. Somesh Awasthi.
 


 

Comment
Article Tags: