Coding Interview PatternsWord Pattern
EasyHash Maps
Word Pattern
Explanation & Solution
Description
Given a pattern and a string s, find if s follows the same pattern.
Here follows means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Specifically:
- Each letter in
patternmaps to exactly one unique word ins. - Each unique word in
smaps to exactly one letter inpattern. - No two letters map to the same word, and no two words map to the same letter.
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Explanation: The bijection is: 'a' -> "dog", 'b' -> "cat".
Constraints
1 <= pattern.length <= 300patterncontains only lower-case English letters1 <= s.length <= 3000scontains only lower-case English letters and spaces' 'sdoes not contain any leading or trailing spaces- All the words in
sare separated by a single space
Approach
Hash Maps pattern
1. Split the String Into Words
- Split
sby spaces to get an array of words - If the number of words does not equal the length of
pattern, returnfalseimmediately
2. Create Two Hash Maps
charToWordmaps each pattern character to a wordwordToCharmaps each word back to a pattern character- Two maps enforce the bijection requirement
3. Iterate Through Pattern and Words Together
- For each index
i, pairpattern[i]withwords[i]
4. Check for Conflicts
- If the character already maps to a different word, return
false - If the word already maps to a different character, return
false - This catches both one-to-many and many-to-one violations
5. Record the Mapping
- Store
pattern[i] -> words[i]incharToWord - Store
words[i] -> pattern[i]inwordToChar
6. Return True
- If the entire pattern is processed without conflicts, the string follows the pattern
Key Insight
- This problem is essentially the same as Isomorphic Strings, but instead of mapping characters to characters, we map characters to words. The dual-map technique ensures the bijection property in both directions.
Time
O(n + m)where n is the pattern length and m is the length of string sSpace
O(n)each map stores at most n entriesVisualization
Input:
[d, o, g, , c, a, t, , c, a, t, , d, o, g]
—
No animation available
Left (L)Right (R)ConvergedDone
0 steps