#151

Reverse Words in a String

Medium Split & rebuild

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Reverse the order of words in a string. Remove leading, trailing and repeated spaces.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: reverse the word order and clean up spaces.

Why this works: split on runs of spaces, then join the words from last to first with single spaces.

Example: " the sky is blue "

words: [the, sky, is, blue]→ "blue is sky the"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

split(" ") on raw input produces empty strings for repeated spaces.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Strings
🎬 Episodes 16–20: video coming soon