VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-a-string/

⇱ Reverse a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse a String

Last Updated : 7 Mar, 2026

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.

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.


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.

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.

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.



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.


Output
efcdba


Note: C does not provide a standard built-in function to reverse strings.

Comment
Article Tags: