Practice Problem
Word Pattern
Difficulty: Easy
Check if a string of words follows the same pattern as a given pattern string, using a bijective character-to-word mapping.
Word Pattern
Given a pattern and a string s, determine if s follows the same pattern.
"Follows" means there is a bijection (one-to-one mapping) between each letter in pattern and each non-empty word in s. Specifically:
- Each letter in
patternmaps to exactly one unique word. - Each word maps to exactly one unique letter.
- No two letters map to the same word, and no two words map to the same letter.
Examples
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Explanation: 'a' -> "dog", 'b' -> "cat". The mapping is consistent.Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Explanation: 'a' maps to "dog" at index 0 but would need to map to "fish" at index 3.Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Explanation: 'a' would need to map to both "dog" and "cat".Constraints
1 <= pattern.length <= 300patterncontains only lowercase English letters.1 <= s.length <= 3000scontains only lowercase English letters and spaces.shas no leading or trailing spaces.- Words in
sare separated by a single space.
Expected Complexity
- Time: O(n + m) where n is the pattern length and m is the string length
- Space: O(n) for the mappings
EASY
Arrays
Hash Map / Dictionary
Strings
Beginner
0 views
Solution
Hints
Hint 1
Hint 2
Premium
Hint 3
Premium
This section is available for CodeSnatch Premium members only.
