Home
DSA Patterns
Hash Map
Word Pattern
Word Pattern (LeetCode 290)
Word Pattern (LeetCode 290): check whether a string of words follows a letter pattern with two hash maps, letter to word and word to letter, after checking the counts match.
Problem Understanding
Word Pattern: given a pattern of letters and a string s of space-separated words, decide whether s follows the pattern. Each letter must map to exactly one word and each word to exactly one letter, a bijection.
Example: pattern = "abba", s = "dog cat cat dog" returns true; with s = "dog cat cat fish" it returns false.
The Intuition: Isomorphic Strings With Words
This is Isomorphic Strings where one side is words instead of letters. Split s into words and pair pattern[i] with words[i].
- Different counts: return
falsestraight away. - Letter → word map: a letter that already means another word is a clash.
- Word → letter map: a word that already belongs to another letter is a clash.
- Otherwise record the pair in both hash maps.
Both directions matter: "ab" and "dog dog" pass the first map but fail the second.
Word Pattern Visualization
SAME LENGTH: EMPTY MAPS
pattern letter over word
letter → word
Empty
word → letter
Empty
4 letters, 4 words. Two empty maps: letter → word and word → letter
Next
New pair: record 'a' → "dog" both ways
pattern
s
Each column stacks a pattern letter over its word; both maps are beside the figure. Try Word reused to see a clash only the word → letter map catches.
Word Pattern Dry Run
Input: pattern = "abba", s = "dog cat cat fish"
| Pair | Letter map | Word map | Result |
|---|---|---|---|
| a, dog | new | new | record |
| b, cat | new | new | record |
| b, cat | b → cat ✓ | cat → b ✓ | ok |
| a, fish | a → dog ✗ | - | clash |
Answer: false.
Word Pattern LeetCode Solution
Split, compare counts, then two maps. C has no hash map, so it compares every pair of positions instead: two positions must have equal letters exactly when they have equal words (O(n²), fine for LeetCode's limits).
Word Pattern Code
1var wordPattern = function(pattern, s) {2 const words = s.split(' ');3 if (words.length !== pattern.length) return false;4 const pToW = new Map(), wToP = new Map();5 for (let i = 0; i < words.length; i++) {6 const p = pattern[i], w = words[i];7 if ((pToW.has(p) && pToW.get(p) !== w) || (wToP.has(w) && wToP.get(w) !== p)) return false;8 pToW.set(p, w);9 wToP.set(w, p);10 }11 return true;12};
Word Pattern in Python, Java, C++, TypeScript and C
Word Pattern in Python
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
if len(words) != len(pattern):
return False
p_to_w, w_to_p = {}, {}
for p, w in zip(pattern, words):
if p_to_w.get(p, w) != w or w_to_p.get(w, p) != p:
return False
p_to_w[p] = w
w_to_p[w] = p
return TrueWord Pattern in Java
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) return false;
Map<Character, String> pToW = new HashMap<>();
Map<String, Character> wToP = new HashMap<>();
for (int i = 0; i < words.length; i++) {
char p = pattern.charAt(i);
String w = words[i];
if (pToW.containsKey(p) && !pToW.get(p).equals(w)) return false;
if (wToP.containsKey(w) && wToP.get(w) != p) return false;
pToW.put(p, w);
wToP.put(w, p);
}
return true;
}
}Word Pattern in C++
class Solution {
public:
bool wordPattern(string pattern, string s) {
vector<string> words;
stringstream ss(s);
string w;
while (ss >> w) words.push_back(w);
if (words.size() != pattern.size()) return false;
unordered_map<char, string> pToW;
unordered_map<string, char> wToP;
for (int i = 0; i < (int)words.size(); i++) {
char p = pattern[i];
if (pToW.count(p) && pToW[p] != words[i]) return false;
if (wToP.count(words[i]) && wToP[words[i]] != p) return false;
pToW[p] = words[i];
wToP[words[i]] = p;
}
return true;
}
};Word Pattern in TypeScript
function wordPattern(pattern: string, s: string): boolean {
const words = s.split(' ');
if (words.length !== pattern.length) return false;
const pToW = new Map<string, string>(), wToP = new Map<string, string>();
for (let i = 0; i < words.length; i++) {
const p = pattern[i], w = words[i];
if ((pToW.has(p) && pToW.get(p) !== w) || (wToP.has(w) && wToP.get(w) !== p)) return false;
pToW.set(p, w);
wToP.set(w, p);
}
return true;
}Word Pattern in C
bool wordPattern(char* pattern, char* s) {
int n = strlen(pattern), count = 0;
char* words[1500];
for (char* w = strtok(s, " "); w && count < 1500; w = strtok(NULL, " ")) words[count++] = w;
if (count != n) return false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
bool samePattern = pattern[i] == pattern[j];
bool sameWord = strcmp(words[i], words[j]) == 0;
if (samePattern != sameWord) return false;
}
}
return true;
}Edge Cases & Common Mistakes
- Count mismatch:
"aaa"with"dog dog"must return false before any map lookup. - Only one map:
"ab"/"dog dog"slips past a letter → word map alone. - Java boxing:
wToP.get(w) != pcompares aCharacterwith achar, which unboxes and compares values; comparing twoCharacterobjects with!=would compare references. - Splitting: LeetCode guarantees single spaces and no leading or trailing ones;
split()in Python handles any whitespace anyway.
Summary
Split s into words and return false if the count differs from the pattern length. Then walk letters and words together with two maps, letter → word and word → letter; any disagreement means false. O(n + m) time and space.
More practice: DSA interview questions with answers · patterns cheat sheet
