Word Pattern
LeetCode 290 | Difficulty: Easyβ
EasyProblem Descriptionβ
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.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Explanation:
The bijection can be established as:
- `'a'` maps to `"dog"`.
- `'b'` maps to `"cat"`.
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Constraints:
- `1 <= pattern.length <= 300`
- `pattern` contains only lower-case English letters.
- `1 <= s.length <= 3000`
- `s` contains only lowercase English letters and spaces `' '`.
- `s` **does not contain** any leading or trailing spaces.
- All the words in `s` are separated by a **single space**.
Topics: Hash Table, String
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 108 ms)β
| Metric | Value |
|---|---|
| Runtime | 108 ms |
| Memory | 36.5 MB |
| Date | 2022-02-08 |
public class Solution {
public bool WordPattern(string pattern, string s) {
Dictionary<string, int> d = new Dictionary<string, int>();
string[] words = new string[26];
string[] arr = s.Split(new char[] { ' ' }).ToArray();
if (pattern.Length != arr.Length) return false;
for (int i = 0; i < pattern.Length; i++)
{
int index = pattern[i] - 'a';
if (string.IsNullOrEmpty(words[index]))
{
if(d.ContainsKey(arr[i])) return false;
words[index] = arr[i];
d.Add(arr[i], index);
}
else if (arr[i] != words[index])
return false;
}
return true;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Hash map gives O(1) lookup β think about what to use as key vs value.