LeetCode 290: Word Pattern — Python Solution

LeetCode 290: Word Pattern is an Easy hashmap problem. This Python walkthrough develops a bidirectional token mapping 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.

DifficultyEasy
TopicHashmap
Reusable patternbidirectional token mapping
ComplexityO(n) time and O(k) space

Recognizing the pattern

A hash table converts a repeated search for prior information into an average constant-time lookup.

For this problem specifically, split the sentence into words and enforce a one-to-one mapping between pattern characters and words. The invariant worth writing beside the code is: Both maps agree for every processed pattern-word pair.

Step-by-step algorithm

  1. Identify the input state consumed by wordPattern(pattern, s) and initialize the data required by the bidirectional token mapping pattern.
  2. Split the sentence into words and enforce a one-to-one mapping between pattern characters and words.
  3. After each update, verify the page’s central invariant: Both maps agree for every processed pattern-word pair.
  4. Finish only after the boundary behavior is covered: The number of words must equal the pattern length.

Python solution

class Solution:
    def wordPattern(self, pattern, s):
        words = s.split()
        if len(pattern) != len(words): return False
        forward, backward = {}, {}
        for char, word in zip(pattern, words):
            if (char in forward and forward[char] != word) or (word in backward and backward[word] != char): return False
            forward[char], backward[word] = word, char
        return True

Reading the implementation

The main entry point is wordPattern(pattern, s). The named working state includes words, forward; those variables make the bidirectional token mapping state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, split the sentence into words and enforce a one-to-one mapping between pattern characters and words.

Correctness argument

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

Preservation. Split the sentence into words and enforce a one-to-one mapping between pattern characters and words. Each update records the current item without invalidating earlier decisions; consequently, both maps agree for every processed pattern-word pair.

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(k) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). 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().wordPattern("abba","dog cat cat dog")

Common mistakes and edge cases

  • Problem-specific boundary: The number of words must equal the pattern length.
  • Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
  • Invariant check: after every update, confirm that both maps agree for every processed pattern-word pair.

Interview review checklist

  • Explain why bidirectional token mapping matches the structure of this input.
  • State the invariant in one sentence before tracing code: Both maps agree for every processed pattern-word pair.
  • Derive O(n) time and O(k) space from how many times each element or state is visited.
  • Test the boundary explicitly: The number of words must equal the pattern length.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 205. Isomorphic Strings · Next: 242. Valid Anagram