Reverse a string without using recursion

Write an iterative program to reverse a given string.

 

For example,

Input: “Techie Delight”
Output: “thgileD eihceT”

 


 

Approach 1: Using build-in methods

Simple approach will be to use strrev() function in C or std::reverse in C++ or StringBuilder.reverse() method in java.

C++

Download   Run Code

Java

Download   Run Code


 

Approach 2: Using stack

We can easily reverse a given string using stack data structure. We initially push every character of the string into the stack and then we start filling the input string (starting from index 0) by popping characters from the stack until it is empty.

C++

Download   Run Code

 
The time complexity of above solution is O(n) and auxiliary space used by the program is O(n) for stack.
 

Approach 3: in-place conversion

Above solution takes O(n) for stack which is not recommended. We can easily solve this problem in linear time and O(1) space. Below is the iterative in-place solution –

C++

Download   Run Code

 
Related Posts: Reverse a string using recursion

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂