Reverse String Word Wise

Moderate
0/80
102 upvotes
Asked in companies
Info Edge India (Naukri.com)CIS - Cyber InfrastructureAmazon

Problem statement

Reverse the given string word-wise. The last word in the given string should come at 1st place, the last-second word at 2nd place, and so on. Individual words should remain as it is.

Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first and only line of input contains a string without any leading and trailing spaces.
Output format :
The only line of the output prints the Word wise reversed string.
Constraints :
0 <= |S| <= 10^5
where |S| represents the length of string, S.
Sample Input 1:
Welcome to Coding Ninjas
Sample Output 1:
Ninjas Coding to Welcome
Sample Input 2:
Always indent your code
Sample Output 2:
code your indent Always
Approaches (1)
Two Pointers approach
  • We first split the input string on the basis of spaces and store it in another array of words.
  • We then initialize two pointers i and j with initial values 0 and length of words - 1.
  • Now we proceed like palindrome reversal.
    • We iterate while i < j
    • swap words[i] and words[j].
    • increment i and decrement j.
  • Finally, we concatenate this array of words using spaces again and return the output.
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Reverse String Word Wise
Full screen
Console