Skip to content

Reverse Words in a String

MediumTwo Pointers
Decode it first. Clues, constraints, pattern and plan before any code.

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.

s = "the sky is blue"     →  "blue is sky the"
s = "  hello world  "     →  "world hello"
s = "a good   example"    →  "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.