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 - Bijection Mapping INPUT pattern = "abba" a b b a s = "dog cat cat dog" dog cat cat dog Requirements: 1. Each letter maps to one word 2. Each word maps to one letter 3. Bijection (1-to-1 both ways) 0 1 2 3 ALGORITHM STEPS 1 Split string into words ["dog","cat","cat","dog"] 2 Check length match pattern.len == words.len 3 Create two hash maps char-->word, word-->char 4 Iterate and validate Check both mappings match Hash Maps State: char-->word a: "dog" b: "cat" word-->char "dog": a "cat": b All mappings consistent [OK] FINAL RESULT true Pattern Match Verified! Mapping Verification: Index 0: a-->dog [OK] Index 1: b-->cat [OK] Index 2: b-->cat [OK] Index 3: a-->dog [OK] Bijection Confirmed No conflicts in either map Output: true Key Insight: A bijection requires TWO hash maps to ensure both directions are consistent. Using only one map (char-->word) would miss cases like pattern="abba" with s="dog dog dog dog" where multiple chars map to the same word. Time: O(n), Space: O(n) where n is the number of characters/words. TutorialsPoint - Word Pattern | Two Hash Maps (Bidirectional Mapping)
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