Word Pattern - Problem
Given a pattern and a string s, find if s follows the same pattern.
Here follow 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 & Output
Example 1 — Basic Pattern Match
$
Input:
pattern = "abba", s = "dog cat cat dog"
›
Output:
true
💡 Note:
Pattern 'a' maps to 'dog' and 'b' maps to 'cat'. The sequence abba becomes dog-cat-cat-dog, which matches the input string exactly.
Example 2 — Bijection Violation
$
Input:
pattern = "abba", s = "dog cat cat fish"
›
Output:
false
💡 Note:
Pattern 'a' first maps to 'dog', but then would need to map to 'fish' in the last position. This violates the bijection requirement.
Example 3 — Length Mismatch
$
Input:
pattern = "aaaa", s = "dog dog dog"
›
Output:
false
💡 Note:
Pattern has 4 characters but string has only 3 words. They must have equal length for a valid pattern match.
Constraints
- 1 ≤ pattern.length ≤ 300
- pattern contains only lower-case English letters
- 1 ≤ s.length ≤ 3000
- s contains only lowercase English letters and spaces ' '
Visualization
Tap to expand
Understanding the Visualization
1
Input
Pattern 'abba' and string 'dog cat cat dog'
2
Mapping
Each pattern character maps to exactly one unique word
3
Verification
Check if mapping is consistent and bijective
Key Takeaway
🎯 Key Insight: Use two hash maps to ensure bijective mapping - each character maps to exactly one word and each word maps to exactly one character
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code