Last Updated: 16 Mar, 2021

Reverse String Word Wise

Moderate
Asked in companies
BarclaysInnovaccerAmazon

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.

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.

Approaches

01 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.