Last Updated: 11 Dec, 2021

String Reverse

Easy
Asked in companies
Housing.comNagarro SoftwareBirlasoft Ltd.

Problem statement

You are having a string ‘S’ containing ASCII characters.


You are required to reverse the input string.


Output the reverse of the string ‘S’.


Example :
S = “hello”

Explanation : 

The reverse of the string ‘S’ is “olleh”.
Input Format :
The first line contains an integer 'T' which denotes the number of test cases to be run. Then the test cases follow.

The only line of each test case contains a string ‘S’.


Output format :
For each test case, print a string denoting the reverse of the string ‘S’.

Print the output of each test case in a new line.


Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.


Constraints :
1 <= T <= 5
1 <= S.length <= 10^5

Time Limit: 1 sec

Approaches

01 Approach

 

Approach : 

 

  • We can observe that when a string is reversed, the first character becomes the last character, the second character becomes the second last character and so on.
  • Example :
    • For the string “abcd” , the reverse is “dcba”.
    • The first character was initially ‘a’, but after reversing it is the last character.
    • Similarly, the second character was initially ‘b’ which after reversing is the second last character.
  • So, for reversing a string, we can swap its ‘S[0]’ and ‘S[N-1]’ characters, ‘S[1]’ and ‘S[N–2]’ characters and so on.
  • We need to swap ‘S[i]’ with ‘S[N-i-1]’ for all ‘i’ < ‘N/2’.
  • We traverse till ‘i’ < ‘N/2’ only as after that, it again starts swapping the previously swapped pairs and if we perform operations till ‘i=N-1’ we will get the original string only.


 

Algorithm : 

 

  • Run a for loop from ‘i=0’ to ‘i=(N/2) - 1’  :
    • Swap ‘S[i]’ and ‘S[N-i-1]’.
  • Return ‘S’ as the final string.