CodingNodes / Arrays & Hashing / Reverse Words in a String System design Space play · ←→ step · R restart

Problem

A word is a run of non-space characters. Given a string s, return a string that has the same words in reverse order, separated by exactly one space.

s may have extra spaces at the start or end, or several spaces between words. The result must have none of these: no leading or trailing space, and a single space between neighbouring words. The letters inside each word keep their original order.

Constraints

  • 1 ≤ s.length ≤ 10⁴
  • s contains letters, digits and spaces
  • s contains at least one word

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: The pointer i moves left across each character once, and each word is copied once.

Space: The result string holds every letter of s plus the single spaces between words.

Walk from the end of the string. Skip spaces; when you hit a letter, remember where the word ends, keep moving left to find where it starts, and append that word to the result. Because we go right to left, the words come out already reversed, and we add a space only between words.