Reverse string without using any temporary variable
Last Updated :
07 Jul, 2022
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.
C++
// C++ Program to reverse a string without
// using temp variable
#include <bits/stdc++.h>
using namespace std;
// Function to reverse string and return reversed string
string reversingString(string str, int start, int end)
{
// Iterate loop upto start not equal to end
while (start < end)
{
// XOR for swapping the variable
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
return str;
}
// Driver Code
int main()
{
string s = "GeeksforGeeks";
cout << reversingString(s, 0, 12);
return 0;
}
Java
// Java Program to reverse a string without
// using temp variable
import java.util.*;
class GFG
{
// Function to reverse string and
// return reversed string
static String reversingString(char []str,
int start,
int end)
{
// Iterate loop upto start not equal to end
while (start < end)
{
// XOR for swapping the variable
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
return String.valueOf(str);
}
// Driver Code
public static void main(String[] args)
{
String s = "GeeksforGeeks";
System.out.println(reversingString
(s.toCharArray(), 0, 12));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 Program to reverse a string
# without using temp variable
# Function to reverse string and
# return reversed string
def reversingString(str, start, end):
# Iterate loop upto start not equal to end
while (start < end):
# XOR for swapping the variable
str = (str[:start] + chr(ord(str[start]) ^
ord(str[end])) +
str[start + 1:]);
str = (str[:end] + chr(ord(str[start]) ^
ord(str[end])) +
str[end + 1:]);
str = (str[:start] + chr(ord(str[start]) ^
ord(str[end])) +
str[start + 1:]);
start += 1;
end -= 1;
return str;
# Driver Code
s = "GeeksforGeeks";
print(reversingString(s, 0, 12));
# This code is contributed by 29AjayKumar
C#
// C# Program to reverse a string without
// using temp variable
using System;
class GFG
{
// Function to reverse string and
// return reversed string
static String reversingString(char []str,
int start,
int end)
{
// Iterate loop upto start
// not equal to end
while (start < end)
{
// XOR for swapping the variable
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
return String.Join("", str);
}
// Driver Code
public static void Main(String[] args)
{
String s = "GeeksforGeeks";
Console.WriteLine(reversingString
(s.ToCharArray(), 0, 12));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to reverse a string
// without using temp variable
// Function to reverse string and
// return reversed string
function reversingString(str, start, end)
{
// Iterate loop upto start not
// equal to end
while (start < end)
{
// XOR for swapping the variable
str[start] = String.fromCharCode(
str[start].charCodeAt(0) ^
str[end].charCodeAt(0));
str[end] = String.fromCharCode(
str[end].charCodeAt(0) ^
str[start].charCodeAt(0));
str[start] = String.fromCharCode(
str[start].charCodeAt(0) ^
str[end].charCodeAt(0));
++start;
--end;
}
return(str).join("");
}
// Driver Code
let s = "GeeksforGeeks";
document.write(reversingString(
s.split(""), 0, 12));
// This code is contributed by rag2127
</script>
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.
C++
// Reversing a string using reverse()
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str = "geeksforgeeks";
// Reverse str[begin..end]
reverse(str.begin(), str.end());
cout << str;
return 0;
}
Java
// Reversing a string using reverse()
class GFG
{
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("geeksforgeeks");
// Reverse str[begin..end]
str.reverse();
System.out.println(str);
}
}
// This code is contributed
// by PrinciRaj1992
Python3
# Reversing a string using reverse()
str = "geeksforgeeks";
# Reverse str[begin..end]
str = "".join(reversed(str))
print(str);
# This code is contributed by 29AjayKumar
C#
// Reversing a string using reverse()
using System;
using System.Linq;
class GFG
{
public static void Main(String[] args)
{
String str = "geeksforgeeks";
// Reverse str[begin..end]
str = new string(str.Reverse().ToArray());
Console.WriteLine(str);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Reversing a string using reverse()
function reverseString(str) {
return str.split("").reverse().join("");
}
var str = ("geeksforgeeks");
document.write(reverseString(str));
// This code is contributed by todaysgaurav
</script>
Output:
skeegrofskeeg
Time complexity : O(n)
Auxiliary Space : O(1)
This article is contributed by Aarti_Rathi and Mr. Somesh Awasthi.
Reverse string without using any temporary variable
Similar Reads
Reverse a String â Complete Tutorial Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on.Examples:Input: s = "GeeksforGeeks"Output: "skeeGrofskeeG"Explanation : The first character G mo
13 min read
Easiest Way to Reverse a String Have you wondered which is the easiest way to reverse a string, Imagine you are giving a contest and an algorithm you have made requires reversing a string, you must be aware of the easiest way to reverse a string. What is a reversal of string:Reversing a string is the technique that reverses or cha
4 min read
How to reverse a String in Python Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Letâs see how it works:Using string slicingThis slicing method is one of the s
4 min read
Reverse the given string in the range [L, R] 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" I
4 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
Reverse an array upto a given position Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k). Example: Input: arr[] = {1, 2, 3, 4, 5, 6} k = 4 Output: arr[] = {4, 3, 2, 1, 5, 6} We strongly reco
6 min read