Word Pattern
Check whether the words of a string follow a letter pattern, with each letter standing for exactly one word.
Given a string patternstruespatterns
Example 1
Output: true
Example 2
Output: false
Explanation: a would stand for both "dog" and "fish".
Example 3
Output: false
Explanation: a and b would both stand for "cat".
The Idea
Poets often mark which lines of a poem rhyme by giving them letters. The letters abba mean that the first and last lines rhyme, and so do the two middle lines. This problem uses letters the same way, but with whole words. The pattern abba
Look at the picture below. Each row puts the letters of abbatrue
In the row labelled Example 2, the last position is marked in orange. The second a sits above fish, but a already stands for dog. One letter cannot stand for two words, so the answer is false
Example 3 is trickier. Taken on its own, each letter looks fine: a always sits above cat, and so does b. The pairing breaks at the second position, marked in orange, where b meets cat, but cat already belongs to a. If two letters could share one word, the pattern abbaaaaa
So what must we remember as we walk along the pattern? Remembering which word each letter stands for catches Example 2, but not Example 3. We also need to remember which letter each word belongs to. A pairing that holds in both directions like this is called a one-to-one pairing, or a bijection.
The check is therefore one walk from left to right that keeps two tables, one from letter to word and one from word to letter. It stops at the first position where either table disagrees with what it sees.
Solution Approach
Turning that idea into code means settling three things: what happens when the numbers of letters and words differ, where the pairings are kept, and how to record and check a pairing in one step.
Counting letters and words
What if patterns"aaa""dog dog"falsespattern
Where the pairings are kept
Could we manage without tables? The words follow the pattern exactly when, for every two positions, the letters there are equal precisely when the words there are equal. Checking every two positions works, but with n positions that is about n²/2 comparisons.
Two hash maps do the same job in one walk. A hash map stores pairs of a key and a value, and finds the value for a key in about one step. letterToWordwordToLetter
Recording and checking in one step
What happens to each map at a position? Either its key is new, and the pairing should be stored, or the key is known, and the stored partner must match. Java's Map.putIfAbsent(key, value)null
Java Solution
The method wordPattern
- First, split
into the arrays withwords , and returns.split(" ") iffalse differs fromwords.length .pattern.length() - Create the two maps,
andletterToWord , both emptywordToLetter s.HashMap - Walk the positions with one loop over
. At each position, take the letteri and the wordc = pattern.charAt(i) .w = words[i] - Call
on both maps. The resultputIfAbsent is the wordmapped already stands for, andc is the letterback already belongs to, orw when the key was new. If either one is notnull and differs fromnull orw , returnc .false is aback object andCharacter a plainc , sochar compares the two letters as values.back != c - If the loop reaches the end, every position agreed with both maps, so return
.true
The main"abc""dog cat dog""aaa""dog dog"
import java.util.HashMap;
import java.util.Map;
public class WordPattern {
public static boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (words.length != pattern.length()) {
return false; // a letter or a word would have no partner
}
Map<Character, String> letterToWord = new HashMap<>();
Map<String, Character> wordToLetter = new HashMap<>();
for (int i = 0; i < words.length; i++) {
char c = pattern.charAt(i);
String w = words[i];
String mapped = letterToWord.putIfAbsent(c, w);
Character back = wordToLetter.putIfAbsent(w, c);
if ((mapped != null && !mapped.equals(w)) || (back != null && back != c)) {
return false; // the pairing breaks in one direction
}
}
return true;
}
public static void main(String[] args) {
System.out.println(wordPattern("abba", "dog cat cat dog"));
System.out.println(wordPattern("abba", "dog cat cat fish"));
System.out.println(wordPattern("abba", "cat cat cat cat"));
System.out.println(wordPattern("abc", "dog cat dog"));
System.out.println(wordPattern("aaa", "dog dog"));
System.out.println(wordPattern("a", "dog"));
}
}
Running it prints:
true
false
false
false
false
true
Look at the second and third lines. Both are false"dog cat cat fish""cat cat cat cat"
The fourth line, false"abc""dog cat dog"wordToLetterletterToWordtruetrue
The fifth line is false"dog dog"
The original implementation,
Complexity
The work is one split of s
- Time: O(n), with n the number of characters in
.s reads each character ofsplit once, and the twos calls at a position hash and compare one word, so over the whole walk each character ofputIfAbsent is read a fixed number of times.s - Space: O(n). The
array andwords hold the words ofwordToLetter , at most n characters in all, ands has one entry per different letter.letterToWord
With single characters in place of words, the same two-way check solves