Skip to content
MediumStringsAI interview only

Reverse Words in a String

Asked atmicrosoftamazonmetaapplebloomberggoogle

01 · Problem

You are given a string s made of words separated by spaces. A word is any maximal run of non-space characters.

Return a new string containing the same words in reverse order, joined by exactly one space. The input may have leading spaces, trailing spaces, or several spaces between two words; none of that extra spacing should appear in the output (no leading or trailing spaces, no double spaces). The characters inside each word keep their original order.

02 · Examples

Example 01
Input
s = "code runs fast today"
Output
"today fast runs code"

The four words are reversed and joined by single spaces.

Example 02
Input
s = "   keep it simple "
Output
"simple it keep"

Leading and trailing spaces are dropped from the result.

Example 03
Input
s = "data   meets   logic"
Output
"logic meets data"

Each run of three spaces between words collapses to a single space.

03 · Constraints

  • 011 <= s.length <= 104
  • 02s contains English letters (upper and lower case), digits, and spaces ' '
  • 03s contains at least one word

04 · Optimal complexity

Time
O(n)
Space
O(n)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.