"Word Pattern" asks if a pattern string and a space-separated string s follow the same structure. For example, if the pattern is abba, then s must consist of four words where the first and last words are the same, and the middle two words are the same (but different from the first). It is essentially a problem of finding a Bijective Mapping (one-to-one correspondence) between characters and words.
This "Easy" problem is common at companies like Apple and Amazon. It tests basic Hash Table usage and the ability to handle mapping constraints. A common pitfall is ensuring the mapping is unique in both directions: two different characters shouldn't map to the same word, and vice versa.
The pattern is Hash Mapping. You can use two hash maps (or one hash map and one set) to store the pairings:
charToWord map.wordToChar map.
Iterate through the pattern and the words of s simultaneously. If a mapping already exists but doesn't match the current pair, return false.Pattern: xyyx, String: dog cat cat dog.
x -> dog. Store x: dog and dog: x.y -> cat. Store y: cat and cat: y.y -> cat. Map has y: cat. Match!x -> dog. Map has x: dog. Match!
Result: True.pattern="abba", s="dog dog dog dog".Always think about "bijectivity" when you see mapping problems. Using two maps is a safe and clear way to ensure that the relationship is strictly one-to-one.