Reverse Words in a String: Problem Statement
You are given a string of length N
. Your task is to reverse the string word by word. The input may contain multiple spaces between words and may have leading or trailing spaces. The output should have words separated by a single space with no leading or trailing spaces.
Input:
The first line of input contains an integer T
, denoting the number of test cases. Each of the next T
lines contains a string to be reversed word by word.
Output:
For each test case, print the reversed string with one space between words and no leading or trailing spaces.
Example:
If the input string is " Welcome to Coding Ninjas", the output should be "Ninjas Coding to Welcome".
Constraints:
- 1 <=
T
<= 50 - 0 <=
N
<= 105
Time Limit: 1 sec
Note:
Do not print anything in your function. Consider using a mutable data type if strings in your language are immutable.

AnswerBot
4mo
Reverse words in a string word by word, removing leading/trailing spaces and extra spaces between words.
Split the input string by spaces to get individual words
Reverse the order of the words
Join the r...read more
Help your peers!
Add answer anonymously...
JPMorgan Chase & Co. Software Developer Intern interview questions & answers
A Software Developer Intern was asked Q. Count Subarrays with Given XOR Problem Statement You are given an array of integ...read more
A Software Developer Intern was asked Q. Kth Largest Number Problem Statement You are given a continuous stream of number...read more
A Software Developer Intern was asked Q. Stack using Two Queues Problem Statement Develop a Stack Data Structure to store...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked Q1. Count Subarrays with Given XOR Problem Statement You are given an array of integ...read more
A Software Developer Intern was asked Q2. Kth Largest Number Problem Statement You are given a continuous stream of number...read more
A Software Developer Intern was asked Q3. Stack using Two Queues Problem Statement Develop a Stack Data Structure to store...read more
>
JPMorgan Chase & Co. Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

