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 pattern maps to exactly one unique word in s
  • Each unique word in s maps to exactly one letter in pattern
  • 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
Word Pattern: Bijective Character-Word MappingPattern: abba → Words: dog cat cat dogabbadogcatcatdog✓ Mapping: a↔dog, b↔cat (Bijective)Result: true
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
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
28.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen