LeetCode 151: Reverse Words in a String — Python Solution

LeetCode 151: Reverse Words in a String is a Medium array / string problem. This Python walkthrough develops a token normalization solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicArray / String
Reusable patterntoken normalization
ComplexityO(n) time and O(n) space

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, split on whitespace to discard extra spaces, reverse the word sequence, and join with single spaces. The invariant worth writing beside the code is: The output contains exactly the processed words in reverse order with normalized spacing.

Step-by-step algorithm

  1. Identify the input state consumed by reverseWords(s) and initialize the data required by the token normalization pattern.
  2. Split on whitespace to discard extra spaces, reverse the word sequence, and join with single spaces.
  3. After each update, verify the page’s central invariant: The output contains exactly the processed words in reverse order with normalized spacing.
  4. Finish only after the boundary behavior is covered: Leading, trailing, and repeated internal spaces are removed.

Python solution

class Solution:
    def reverseWords(self, s):
        return " ".join(reversed(s.split()))

Reading the implementation

The main entry point is reverseWords(s). The implementation keeps little named state because each operation can be resolved directly from the current input position.

The method expresses the transformation directly without a general traversal loop. In concrete terms, split on whitespace to discard extra spaces, reverse the word sequence, and join with single spaces.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Split on whitespace to discard extra spaces, reverse the word sequence, and join with single spaces. Each update records the current item without invalidating earlier decisions; consequently, the output contains exactly the processed words in reverse order with normalized spacing.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().reverseWords("  hello world  ") == "world hello"

Common mistakes and edge cases

  • Problem-specific boundary: Leading, trailing, and repeated internal spaces are removed.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that the output contains exactly the processed words in reverse order with normalized spacing.

Interview review checklist

  • Explain why token normalization matches the structure of this input.
  • State the invariant in one sentence before tracing code: The output contains exactly the processed words in reverse order with normalized spacing.
  • Derive O(n) time and O(n) space from how many times each element or state is visited.
  • Test the boundary explicitly: Leading, trailing, and repeated internal spaces are removed.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 14. Longest Common Prefix · Next: 6. Zigzag Conversion