Skip to content
CodeKruPro

Reverse the words in a sentence

Coding problemEasy-MediumAsked in: Capgemini, TCS, Wipro

Given a sentence, return its words in reverse order. The letters inside each word stay as they are.

Words are separated by one or more spaces, and the sentence may start or end with spaces. The result has exactly one space between words and no space at the start or end. A sentence with no words gives an empty string.

Examples

Example 1
Input: sentence = "the sky is blue"
Output: "blue is sky the"
Example 2
Input: sentence = " hello world "
Output: "world hello"
Extra spaces between, before and after the words are dropped.
Example 3
Input: sentence = " "
Output: ""

Constraints

  • The length of sentence is between 0 and 100,000
  • Only the space character separates words
  • Words hold printable ASCII characters other than space

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in