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
Split s into words. If lengths differ, return false. Use two hash maps: p2w (pattern char to word) and w2p (word to pattern char). Iterate together, check consistency.
Time O(n), Space 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.
