Given a pattern string like "abba" and a string s of space-separated words like "dog cat cat dog", determine if s follows the same pattern. That means there is a bijection between each character in the pattern and each word in s. A letter maps to exactly one word, and each word maps to exactly one letter.
This is a classic hash map problem requiring bidirectional mapping. A single hash map is not enough because it only enforces one direction. For example, pattern "abba" with "dog dog dog dog" would be incorrectly accepted with a one-way map (a→dog, b→dog) because both letters map to the same word. A second hash map tracking word→letter catches this violation.
The algorithm splits the words from s and compares the length of the pattern with the word count. Then it iterates through both, building the two maps simultaneously. If at any point a mapping contradicts an existing one, return false. This runs in O(n) time where n is the length of the pattern (or number of words).
Edge cases include empty pattern or empty string, a pattern longer than the word list, and patterns where multiple letters map to the same word.
Example Input & Output
Bijection holds: a→dog, b→cat.
Each a maps to different words.
Last word breaks mapping.
b maps to dog but a already maps to dog.
Empty pattern and empty string match.
Algorithm Flow
Solution Approach
Check if a string follows a given pattern, where each character in the pattern maps to a word in the string. Split the string into words. If the pattern length differs from the word count, return false. Build a bijection map from pattern characters to words and vice versa. If a mapping conflicts, return false.
The bijection ensures the mapping is one-to-one in both directions. 'abba' and 'dog cat cat dog' is valid; 'abba' and 'dog cat cat fish' is not because 'a' would map to both 'dog' and 'fish'.
Time complexity is O(n), space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public boolean solution(String pattern, String s) {
if (pattern.isEmpty() && s.isEmpty()) return true;
String[] words = s.split(" ");
if (pattern.length() != words.length) return false;
Map<Character,String> p2w = new HashMap<>();
Map<String,Character> w2p = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
String w = words[i];
if (p2w.containsKey(ch) && !p2w.get(ch).equals(w)) return false;
if (w2p.containsKey(w) && w2p.get(w) != ch) return false;
p2w.put(ch, w);
w2p.put(w, ch);
}
return true;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
