String Reverse

Easy
0/40
Average time to solve is 10m
profile
Contributed by
53 upvotes
Asked in companies
Housing.comNagarro SoftwareBirlasoft India 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”.
Detailed explanation ( Input/output format, Notes, Images )
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
Sample Input 1 :
2
ninja
MoM


Sample Output 1 :
ajnin
MoM


Explanation Of Sample Input 1 :
For test case 1 we have, 

The reverse of “ninja” is “ajnin”.

So, we output “ajnin” ( without quotes ).

For test case 2 we have, 

The reverse of “MoM” is “MoM” as it is a palindrome.

So, we output “MoM”.


Sample Input 2 :
2
ggUM
Kzk


Sample Output 2 :
MUgg
kzK
Hint

Think about swapping characters to reverse the string.


 

Approaches (1)
Optimal 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.

 

Time Complexity

O(N), where ‘N’ is the length of the string ‘S’.

 

We are traversing the string till ‘N/2’, so the overall time complexity is O(N).

 

Space Complexity

O(1) 
 

Constant extra space is required. Hence, the overall Space Complexity is O(1).
 

Code Solution
(100% EXP penalty)
String Reverse
Full screen
Console