Reverse words in a string
You are given a string of length N. You need to reverse the string word by word. There can be multiple spaces between two words and there can be leading or trailing spaces but in the output reversed string you need to put a single space between two words, and your reversed string should not contain leading or trailing spaces.
For example :
If the given input string is " Welcome to Coding Ninjas", then you should return "Ninjas Coding to Welcome" as the reversed string has only a single space between two words and there is no leading or trailing space.
Input Format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first and only one of each test case contains a string that you need to reverse word by word.
Output Format :
For every test case, print the reversed string such that there should be only one space between two strings and there should not be any trailing space.
Note :
Do not print anything. It has already been taken care of.
If the string data type is immutable in your language, consider using a mutable data type as an alternative.
Follow-up:
If the string data type is mutable in your language, can you solve it in place with O(1) extra space?
Constraints :
1 <= T <= 50
0 <= N <= 10^5
Time Limit: 1 sec
CodingNinjas
author
2y
Steps :
1. Initially, reverse the individual words of the given string one by one.
2. Reverse the whole string from start to end to get the desired output
CodingNinjas
author
2y
Brute force
- Create a String ans to store the reversed string.
- Initialize a variable i to 0 and iterate the whole string through a while loop.
- Skip initial spaces by just incrementing i.
- Create a String th...read more
CodingNinjas
author
2y
Backward Traversal
- If the string is null or empty return an empty string.
- If the string is “ “ then return an empty string.
- Initialize a String ans to store the reversed string.
- Initialize a pointer to th...read more
Add answer anonymously...
Top 24/7 Customer Software Developer interview questions & answers
Popular interview questions of Software Developer
>
24/7 Customer Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app