Reverse Each Word

Easy
0/40
55 upvotes
Asked in company
Setu

Problem statement

Aadil has been provided with a sentence in the form of a string as a function parameter. The task is to implement a function so as to print the sentence such that each word in the sentence is reversed.

Example:
Input Sentence: "Hello, I am Aadil!"
The expected output will print, ",olleH I ma !lidaA".
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. The input string represents the sentence given to Aadil.
Output Format:
The only line of output prints the sentence(string) such that each word in the sentence is reversed. 
Constraints:
0 <= N <= 10^6
Where N is the length of the input string.

Time Limit: 1 second
Sample Input 1:
Welcome to Coding Ninjas
Sample Output 1:
emocleW ot gnidoC sajniN
Sample Input 2:
Always indent your code
Sample Output 2:
syawlA tnedni ruoy edoc
Approaches (1)
Two pointers Approach
  • We maintain two pointers previous and i.
  • Previous stores the last index we encountered a space, and i is the loop variable that moves forward.
  • Initialize previous to -1 and append an extra ‘ ’ at the end to reverse the last word.
  • Whenever we encounter a space we reverse the string between previous + 1 to i - 1. This can be done using a simple string reversal algorithm.
  • Finally, we convert the character array to String and return the output.
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Reverse Each Word
Full screen
Console