Given a string s, 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 moves to last position, the second character e moves to second-last and so on.Input: s = "abdcfe"
Output: "efcdba"
Explanation: The first character a moves to last position, the second character b moves to second-last and so on.
Table of Content
Using Backward Traversal – O(n) Time and O(n) Space
The idea is to create an empty result string. Then traverse from last character of the given string appending each character to the result string.
#include <iostream>
#include <string>
using namespace std;
string reverseString(string& s) {
string res;
// Traverse on s in backward direction
// and add each charecter to a new string
for (int i = s.size() - 1; i >= 0; i--) {
res += s[i];
}
return res;
}
int main() {
string s = "abdcfe";
string res = reverseString(s);
cout << res;
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *reverseString(char *s) {
int n = strlen(s);
char *res = (char *)malloc((n + 1) * sizeof(char));
int j = 0;
// Traverse on s in backward direction
// and add each character to a new string
for (int i = n - 1; i >= 0; i--) {
res[j] = s[i];
j++;
}
// Null-terminate the result string
res[n] = '\0';
return res;
}
int main() {
char s[] = "abdcfe";
char *res = reverseString(s);
printf("%s", res);
return 0;
}
class GfG {
static String reverseString(String s) {
StringBuilder res = new StringBuilder();
// Traverse on s in backward direction
// and add each character to a new string
for (int i = s.length() - 1; i >= 0; i--) {
res.append(s.charAt(i));
}
return res.toString();
}
public static void main(String[] args) {
String s = "abdcfe";
String res = reverseString(s);
System.out.print(res);
}
}
def reverseString(s):
res = []
# Traverse on s in backward direction
# and add each character to the list
for i in range(len(s) - 1, -1, -1):
res.append(s[i])
# Convert list back to string
return ''.join(res)
if __name__ == "__main__":
s = "abdcfe"
print(reverseString(s))
using System;
using System.Text;
class GfG {
static string reverseString(string s) {
StringBuilder res = new StringBuilder();
// Traverse on s in backward direction
// and add each character to a new string
for (int i = s.Length - 1; i >= 0; i--) {
res.Append(s[i]);
}
// Convert StringBuilder to string
return res.ToString();
}
static void Main(string[] args) {
string s = "abdcfe";
string res = reverseString(s);
Console.WriteLine(res);
}
}
function reverseString(s) {
let res = [];
// Traverse on s in backward direction
// and add each character to the array
for (let i = s.length - 1; i >= 0; i--) {
res.push(s[i]);
}
return res.join('');
}
//Driver Code
const s = "abdcfe";
console.log(reverseString(s));
Output
efcdba
Using Two Pointers - O(n) Time and O(1) Space
Start from both ends of the string and keep swapping characters while moving toward the center. Each swap places the correct character in its reversed position, and when both pointers meet in the middle, the entire string becomes reversed.
#include <iostream>
using namespace std;
string reverseString(string &s) {
int left = 0, right = s.length() - 1;
// Swap characters from both ends till we reach
// the middle of the string
while (left < right) {
swap(s[left], s[right]);
left++;
right--;
}
return s;
}
int main() {
string s = "abdcfe";
cout << reverseString(s);
return 0;
}
#include <stdio.h>
#include <string.h>
char* reverseString(char *s) {
int left = 0, right = strlen(s) - 1;
// Swap characters from both ends till we reach
// the middle of the string
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
return s;
}
int main() {
char s[] = "abdcfe";
printf("%s", reverseString(s));
return 0;
}
class GfG {
static String reverseString(String s) {
int left = 0, right = s.length() - 1;
// Use StringBuilder for mutability
StringBuilder res = new StringBuilder(s);
// Swap characters from both ends till we reach
// the middle of the string
while (left < right) {
char temp = res.charAt(left);
res.setCharAt(left, res.charAt(right));
res.setCharAt(right, temp);
left++;
right--;
}
// Convert StringBuilder back to string
return res.toString();
}
public static void main(String[] args) {
String s = "abdcfe";
System.out.println(reverseString(s));
}
}
def reverseString(s):
left = 0
right = len(s) - 1
# Convert string to a list for mutability
s = list(s)
# Swap characters from both ends till we reach
# the middle of the string
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
# Convert list back to string
return ''.join(s)
if __name__ == "__main__":
s = "abdcfe"
print(reverseString(s))
using System;
using System.Text;
class GfG {
static string reverseString(string s) {
// Use StringBuilder for mutability
StringBuilder res = new StringBuilder(s);
int left = 0, right = res.Length - 1;
// Swap characters from both ends till we reach
// the middle of the string
while (left < right) {
char temp = res[left];
res[left] = res[right];
res[right] = temp;
left++;
right--;
}
// Convert StringBuilder back to string
return res.ToString();
}
static void Main(string[] args) {
string s = "abdcfe";
Console.WriteLine(reverseString(s));
}
}
function reverseString(s) {
let left = 0, right = s.length - 1;
// Convert string to array for mutability
s = s.split('');
// Swap characters from both ends till we reach
// the middle of the string
while (left < right) {
[s[left], s[right]] = [s[right], s[left]];
left++;
right--;
}
return s.join('');
}
//Driver Code
const s = "abdcfe";
console.log(reverseString(s));
Using Recursion - O(n) Time and O(n) Space
The idea is to use recursion and define a recursive function that takes a string as input and reverses it. Inside the recursive function,
- Swap the first and last element.
- Recursively call the function with the remaining substring.
#include <iostream>
#include <vector>
using namespace std;
void reverseStringRec(string &s, int l, int r) {
// If the substring is empty, return
if(l >= r)
return;
swap(s[l], s[r]);
// Recur for the remaining string
reverseStringRec(s, l + 1, r - 1);
}
// function to reverse a string
string reverseString(string &s) {
int n = s.length();
reverseStringRec(s, 0, n - 1);
return s;
}
int main() {
string s = "abdcfe";
cout << reverseString(s) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
void reverseStringRec(char *s, int l, int r) {
if (l >= r)
return;
// Swap the characters at the ends
char temp = s[l];
s[l] = s[r];
s[r] = temp;
// Recur for the remaining string
reverseStringRec(s, l + 1, r - 1);
}
char* reverseString(char *s) {
int n = strlen(s);
reverseStringRec(s, 0, n - 1);
return s;
}
int main() {
char s[] = "abdcfe";
printf("%s\n", reverseString(s));
return 0;
}
class GfG {
static void reverseStringRec(char[] s, int l, int r) {
if (l >= r)
return;
// Swap the characters at the ends
char temp = s[l];
s[l] = s[r];
s[r] = temp;
// Recur for the remaining string
reverseStringRec(s, l + 1, r - 1);
}
// Function to reverse a string
static String reverseString(String s) {
char[] arr = s.toCharArray();
reverseStringRec(arr, 0, arr.length - 1);
return new String(arr);
}
public static void main(String[] args) {
String s = "abdcfe";
System.out.println(reverseString(s));
}
}
def reverseStringRec(arr, l, r):
if l >= r:
return
# Swap the characters at the ends
arr[l], arr[r] = arr[r], arr[l]
# Recur for the remaining string
reverseStringRec(arr, l + 1, r - 1)
def reverseString(s):
# Convert string to list of characters
arr = list(s)
reverseStringRec(arr, 0, len(arr) - 1)
# Convert list back to string
return ''.join(arr)
if __name__ == "__main__":
s = "abdcfe"
print(reverseString(s))
using System;
using System.Text;
class GfG {
static void reverseStringRec(StringBuilder s, int l, int r) {
if (l >= r)
return;
char temp = s[l];
s[l] = s[r];
s[r] = temp;
// Recur for the remaining string
reverseStringRec(s, l + 1, r - 1);
}
// function to reverse a string
static string reverseString(string input) {
StringBuilder s = new StringBuilder(input);
int n = s.Length;
reverseStringRec(s, 0, n - 1);
return s.ToString();
}
static void Main() {
string s = "abdcfe";
Console.WriteLine(reverseString(s));
}
}
function reverseStringRec(res, l, r) {
if (l >= r) return;
// Swap the characters at the ends
[res[l], res[r]] = [res[r], res[l]];
// Recur for the remaining string
reverseStringRec(res, l + 1, r - 1);
}
function reverseString(s) {
// Convert string to array of characters
let res = s.split('');
reverseStringRec(res, 0, res.length - 1);
// Convert array back to string
return res.join('');
}
//Driver Code
let s = "abdcfe";
console.log(reverseString(s));
Output
efcdba
Using Stack - O(n) Time and O(n) Space
The idea is to use stack for reversing a string because Stack follows Last In First Out (LIFO) principle. This means the last character you add is the first one you'll take out. So, when we push all the characters of a string into the stack, the last character becomes the first one to pop.
#include <iostream>
using namespace std;
string reverseString(string &s) {
stack<char> st;
// Push the charcters into stack
for (int i = 0; i < s.size(); i++) {
st.push(s[i]);
}
// Pop the characters of stack into the original string
for (int i = 0; i < s.size(); i++) {
s[i] = st.top();
st.pop();
}
return s;
}
int main() {
string s = "abdcfe";
cout << reverseString(s);
return 0;
}
#include <stdio.h>
#include <string.h>
void reverseString(char s[])
{
int n = strlen(s);
char stack[n]; // Stack implemented as array
int top = -1;
// Push characters onto the stack
for (int i = 0; i < n; i++)
{
stack[++top] = s[i];
}
// Pop characters from stack back into the string
for (int i = 0; i < n; i++)
{
s[i] = stack[top--];
}
}
int main()
{
char s[] = "abdcfe";
reverseString(s);
printf("%s\n", s);
return 0;
}
import java.util.*;
class GfG {
static String reverseString(String s) {
Stack<Character> st = new Stack<>();
// Push the characters into stack
for (int i = 0; i < s.length(); i++)
st.push(s.charAt(i));
StringBuilder res = new StringBuilder();
// Pop the characters of stack into the original string
for (int i = 0; i < s.length(); i++)
res.append(st.pop());
return res.toString();
}
public static void main(String[] args) {
String s = "abdcfe";
System.out.println(reverseString(s));
}
}
def reverseString(s):
stack = []
# Push the characters into stack
for char in s:
stack.append(char)
# Prepare a list to hold the reversed characters
rev = [''] * len(s)
# Pop the characters from stack into the reversed list
for i in range(len(s)):
rev[i] = stack.pop()
# Join the list to form the reversed string
return ''.join(rev)
if __name__ == "__main__":
s = "abdcfe"
print(reverseString(s))
using System;
using System.Collections.Generic;
using System.Text;
class GfG {
static string reverseString(string s) {
Stack<char> st = new Stack<char>();
// Push the characters into stack
for (int i = 0; i < s.Length; i++)
st.Push(s[i]);
// Create a StringBuilder to hold the reversed string
StringBuilder res = new StringBuilder();
// Pop the characters from stack into the StringBuilder
while (st.Count > 0)
res.Append(st.Pop());
// Convert the StringBuilder back to a string
return res.ToString();
}
static void Main() {
string s = "abdcfe";
Console.WriteLine(reverseString(s));
}
}
function reverseString(s) {
// To store the characters of the original string.
const stack = [];
// Push the characters into the stack.
for (let i = 0; i < s.length; i++) {
stack.push(s[i]);
}
// Create an array to hold the reversed characters
const res = new Array(s.length);
// Pop the characters of the stack and store in the array
for (let i = 0; i < s.length; i++) {
res[i] = stack.pop();
}
// Join the array to form the reversed string
return res.join('');
}
//Driver Code
let str = "abdcfe";
console.log(reverseString(str));
Output
efcdba
Using Inbuilt methods
The idea is to use built-in reverse method to reverse the string. If built-in method for string reversal does not exist, then convert string to array or list and use their built-in method for reverse. Then convert it back to string.
#include <iostream>
using namespace std;
string reverseString(string &s) {
reverse(s.begin(), s.end());
return s;
}
int main() {
string s = "abdcfe";
cout << reverseString(s) ;
return 0;
}
import java.io.*;
import java.util.*;
class GFG {
static String stringReverse(String s) {
StringBuilder res = new StringBuilder(s);
res.reverse();
return res.toString();
}
public static void main(String[] args) {
String s = "abdcfe";
System.out.println(stringReverse(s));
}
}
def reverseString(s):
# Reverse the string using slicing
return s[::-1]
if __name__ == "__main__":
str = "abdcfe"
print(reverseString(str))
using System;
class GfG {
static string reverseString(string s) {
// Reverse the string using the built-in method
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main() {
string s = "abdcfe";
Console.WriteLine(reverseString(s));
}
}
function reverseString(s) {
// convert to array to make it mutable
s = s.split('');
// Reverse the string using the built-in method
s = s.reverse();
return s.join('');
}
//Driver Code
let str = "abdcfe";
console.log(reverseString(str));
Output
efcdba
Note: C does not provide a standard built-in function to reverse strings.