Word Pattern
LeetCode 290 · Easy · solution, intuition & step-by-step walkthrough
Last-seen index per letter and per word must agree.
This is how I solved Word Pattern (LeetCode 290), an easy problem from the Hashing / Frequency pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Same idea as isomorphic strings, but between pattern letters and words: each letter and its word must have been last seen at the same index.
Approach
- 1
Split s into words; lengths must match.
- 2
Compare stored indices for pattern[i] and words[i].
- 3
Record the current index for both.
How I solved it
Last-seen indicesPythonO(n) time · O(n) space
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
pattern_mpp = {}
s_mpp = {}
words = s.split(" ")
if len(pattern)!=len(words):
return False
for i in range(len(pattern)):
char = pattern[i]
word = words[i]
if pattern_mpp.get(char,-1)!=s_mpp.get(word,-1):
return False
pattern_mpp[char]=i
s_mpp[word]=i
return TrueWord Pattern — FAQ
What is the intuition behind Word Pattern?
Same idea as isomorphic strings, but between pattern letters and words: each letter and its word must have been last seen at the same index.
How do you solve Word Pattern (LeetCode 290)?
1. Split s into words; lengths must match. 2. Compare stored indices for pattern[i] and words[i]. 3. Record the current index for both.
What is the time and space complexity of Word Pattern?
Time: O(n). Space: O(n). (Accepted approach: Last-seen indices.)
What are common mistakes in Word Pattern?
Length mismatch is an immediate False.