Skip to content
Decoder

Reverse Words in a String

Medium

Problem

Given a string s, return its words in reverse order. A word is a run of non-space characters. The input may have leading, trailing, or repeated spaces; the output must have the words separated by a single space with no spaces at the ends.

Example 1

Input
s = "the sky is blue"
Output
"blue is sky the"

Example 2

Input
s = " hello world "
Output
"world hello"

Example 3

Input
s = "a good example"
Output
"example good a"

Try it without split: scan the string with indices.

Constraints

  • 1 <= s.length <= 10^4
  • s contains English letters, digits, and spaces ' '.
  • There is at least one word in s.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.