Word Pattern (LeetCode 290): Solution and Explanation

Easy
Hash Table
String

Given a pattern of letters and a string of space separated words, return true when the words follow the pattern exactly. Every letter must stand for one word, and every word must stand for one letter, so the mapping is a bijection.

Intuition

Line the pattern up against the words: letter 0 with word 0, letter 1 with word 1, and so on. If the counts differ, some letter or word has no partner and the answer is false before any lookup.

A bijection can break in two ways. A letter can meet two different words, as in "aaaa" against "dog cat cat dog". Or a word can meet two different letters, as in "ab" against "dog dog". A single letter-to-word map only catches the first, because 'a' and 'b' each see "dog" just once.

So keep one map per direction. For each pair, check that the letter is either new or already tied to this word, and that the word is either new or already tied to this letter. If both agree, record the pair in both maps and move on.

Approach: Two hash maps

  1. Split s into words. If len(pattern) != len(words), return false.
  2. Create char_to_word and word_to_char.
  3. For each pair (c, w): if c is mapped to a word other than w, return false.
  4. If w is mapped to a letter other than c, return false.
  5. Record char_to_word[c] = w and word_to_char[w] = c.
  6. After every pair agrees, return true.

Step-by-step example

pattern = "abba", s = "dog cat cat dog"
  1. Words are [dog, cat, cat, dog]. 4 letters and 4 words, so continue.
  2. ('a', dog): both are new, record a -> dog and dog -> a.
  3. ('b', cat): both are new, record b -> cat and cat -> b.
  4. ('b', cat): b already maps to cat and cat already maps to b, so it agrees.
  5. ('a', dog): a already maps to dog and dog already maps to a, so it agrees. Return true.

Code: Python, Java, C++

1class Solution:
2    def wordPattern(self, pattern: str, s: str) -> bool:
3        words = s.split()
4        if len(pattern) != len(words):
5            return False
6        char_to_word = {}
7        word_to_char = {}
8        for c, w in zip(pattern, words):
9            if c in char_to_word and char_to_word[c] != w:
10                return False
11            if w in word_to_char and word_to_char[w] != c:
12                return False
13            char_to_word[c] = w
14            word_to_char[w] = c
15        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

Splitting s reads its m characters once, and each of the n pairs does constant time map work (hashing a word costs its length, which sums to m).

Space

O(m)

The word list and the two maps hold at most every word once.

Other approaches

First occurrence index (time O(n + m), space O(m))

Map each letter and each word to the index where it first appeared, then require the two first-seen indices to match at every position. It encodes both directions in one comparison and is the same trick used for Isomorphic Strings.

One map plus a used-word set (time O(n + m), space O(m))

Keep only letter to word, and a set of words already claimed. When a new letter arrives with a word that is already in the set, the word belongs to another letter, so return false.

Common mistakes

  • Checking only the letter to word direction. Pattern "ab" with "dog dog" slips through and returns true.
  • Forgetting the length check. With zip in Python, extra words or extra letters are silently ignored.
  • Splitting on a single space and assuming clean input in languages where the split keeps empty strings. The constraints promise single spaces, but split() with no argument in Python or strings.Fields in Go is the safer habit.
  • In Java, comparing a boxed Character from the map with != works for ASCII letters only because of the Character cache. Prefer .equals or unboxing when values can be larger.

Frequently asked questions

Why do I need two maps for Word Pattern?

One map catches a letter that meets two words. The second catches a word that meets two letters, such as pattern "ab" with s = "dog dog".

How is this different from Isomorphic Strings?

The logic is the same bijection test. Here one side is a list of words instead of characters, so you split the string first and also compare the counts.

What is the time and space complexity of Word Pattern?

O(n + m) time, where n is the pattern length and m is the length of s, and O(m) space for the words and the two maps.