Word Pattern (LeetCode 290): Solution and Explanation
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
- Split
sintowords. Iflen(pattern) != len(words), return false. - Create
char_to_wordandword_to_char. - For each pair
(c, w): ifcis mapped to a word other thanw, return false. - If
wis mapped to a letter other thanc, return false. - Record
char_to_word[c] = wandword_to_char[w] = c. - After every pair agrees, return true.
Step-by-step example
pattern = "abba", s = "dog cat cat dog"
- Words are [dog, cat, cat, dog]. 4 letters and 4 words, so continue.
- ('a', dog): both are new, record a -> dog and dog -> a.
- ('b', cat): both are new, record b -> cat and cat -> b.
- ('b', cat): b already maps to cat and cat already maps to b, so it agrees.
- ('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 True1class Solution {
2 public boolean wordPattern(String pattern, String s) {
3 String[] words = s.split(" ");
4 if (pattern.length() != words.length) {
5 return false;
6 }
7 Map<Character, String> charToWord = new HashMap<>();
8 Map<String, Character> wordToChar = new HashMap<>();
9 for (int i = 0; i < words.length; i++) {
10 char c = pattern.charAt(i);
11 String w = words[i];
12 if (charToWord.containsKey(c) && !charToWord.get(c).equals(w)) {
13 return false;
14 }
15 if (wordToChar.containsKey(w) && wordToChar.get(w) != c) {
16 return false;
17 }
18 charToWord.put(c, w);
19 wordToChar.put(w, c);
20 }
21 return true;
22 }
23}1class Solution {
2public:
3 bool wordPattern(string pattern, string s) {
4 vector<string> words;
5 stringstream ss(s);
6 string w;
7 while (ss >> w) words.push_back(w);
8 if (pattern.size() != words.size()) {
9 return false;
10 }
11 unordered_map<char, string> charToWord;
12 unordered_map<string, char> wordToChar;
13 for (int i = 0; i < (int) words.size(); i++) {
14 char c = pattern[i];
15 const string& word = words[i];
16 if (charToWord.count(c) && charToWord[c] != word) {
17 return false;
18 }
19 if (wordToChar.count(word) && wordToChar[word] != c) {
20 return false;
21 }
22 charToWord[c] = word;
23 wordToChar[word] = c;
24 }
25 return true;
26 }
27};Time and space complexity
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).
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 orstrings.Fieldsin Go is the safer habit. - In Java, comparing a boxed
Characterfrom the map with!=works for ASCII letters only because of the Character cache. Prefer.equalsor 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.