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.
Be the first one to answer
Add answer anonymously...
24/7 Customer Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter