Problem Description
Given a pattern string and a space-separated string s, determine if s follows the same pattern. This means there must be a bijection between each letter in the pattern and a non-empty word in s. In other words, every letter maps to exactly one unique word, and every word maps to exactly one unique letter.
Key Insights
- We need a one-to-one mapping between characters in the pattern and words in s.
- Use two hash maps (or dictionaries): one to map characters to words and another to map words to characters.
- Ensure that the number of words in s equals the length of the pattern.
- Check for any conflict during the mapping process.
Space and Time Complexity
Time Complexity: O(n) where n is the number of words (or the length of the pattern), as we iterate through both simultaneously. Space Complexity: O(n) for the mappings stored in the hash maps.
Solution
The approach is to first split the string s into words and verify that its length matches the length of the pattern. Then, iterate through each letter of the pattern along with the corresponding word, and do the following:
- If the pattern character is not in the char-to-word mapping, assign it, but ensure that the corresponding word is also not already assigned to a different character in the word-to-char mapping.
- If the pattern character already exists in the mapping, check that the mapped word matches the current word.
- Return false at any point a conflict is found; otherwise, return true if the entire pattern is processed without error.
This dual-check via two hash maps ensures the bijection property is maintained.