Last Updated: 12 Feb, 2021

Kevin’s stack problem

Easy
Asked in companies
HSBCZscaler

Problem statement

Kevin has recently learned the concept of “STACK”. During his practice, he got stuck in a problem where he has to reverse a string ‘S’ using a stack. So, he appoints you to help him in reversing the string ‘S’. All you have to do is to find the reversed string.

Please reverse the string using a stack so that Kevin gets to know where he is getting wrong after seeing your solution. It is guaranteed that strings will only be composed of English alphabets.

Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain a string ‘S’.
Output Format:
For each test case, return the reversed string.

Output for every test case will be printed in a separate line.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= |S| <= 10^4

Time limit: 1 sec

Approaches

01 Approach

The basic idea is to push the whole string into a stack (character by character) and then take off each character from the stack one by one. The steps are as follows:

 

  1. Iterate through ‘S’.
    • Push each character into the stack.
  2. Keep removing the top character from the stack until the stack becomes empty. Append each drawn character to the new string.
  3. Return the new string.