Imagine you're a cryptographer trying to decode a secret message! You have a pattern (like a cipher key) and a string of words, and you need to determine if the words follow the exact same pattern as your key.
Given a pattern string and a string s of words separated by spaces, determine if s follows the same pattern. This means there must be a one-to-one correspondence (bijection) between each letter in the pattern and each word in the string.
Rules:
- Each letter in
patternmaps to exactly one unique word ins - Each unique word in
smaps to exactly one letter inpattern - No two letters can map to the same word
- No two words can map to the same letter
Example: Pattern "abba" with string "dog cat cat dog" should return true because 'a' maps to 'dog', 'b' maps to 'cat', and the pattern matches perfectly!
Input & Output
Visualization
Time & Space Complexity
Single pass through pattern and words, with O(1) hash map operations
Two hash maps storing at most n character-word pairs each
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