Word Pattern

Check whether the words of a string follow a letter pattern, with each letter standing for exactly one word.

Given a string pattern of letters and a string s of words separated by single spaces, return true if s follows the pattern. The letter at each position of pattern is paired with the word at the same position of s. The words follow the pattern when each letter always stands for the same word and no two letters stand for the same word.

Example 1
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Explanation: a would stand for both "dog" and "fish".
Example 3
Input: pattern = "abba", s = "cat cat cat cat"
Output: false
Explanation: a and b would both stand for "cat".
Solution

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 asks for a first and last word that are equal, and two middle words that are equal to each other but different from the first.

Look at the picture below. Each row puts the letters of abba above the words of one example, position by position. In the row labelled Example 1, a sits above dog both times and b sits above cat both times. So a stands for dog, b stands for cat, and the answer is true.

The pattern abba above the words of each example. In Example 1, a stands for dog and b for cat. In Example 2 the last a meets fish, but a already stands for dog. In Example 3, b meets cat, but cat already belongs to a.

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 abba would mean nothing more than aaaa.

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 pattern has three letters and s has two words, as in "aaa" with "dog dog"? The third a has no word to stand for, so the answer is false. Splitting s at the spaces gives an array of words, and its length is compared with the length of pattern before anything else. That also keeps the walk from running past the end of either one.

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. letterToWord maps each letter to its word and catches Example 2. wordToLetter maps each word to its letter and catches Example 3.

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) covers both cases. It stores the pair and returns null when the key is new. Otherwise it leaves the map alone and returns the value already stored, which can then be compared with the current word or letter.

Java Solution

The method wordPattern works in these steps:

  1. First, split s into the array words with s.split(" "), and return false if words.length differs from pattern.length().
  2. Create the two maps, letterToWord and wordToLetter, both empty HashMaps.
  3. Walk the positions with one loop over i. At each position, take the letter c = pattern.charAt(i) and the word w = words[i].
  4. Call putIfAbsent on both maps. The result mapped is the word c already stands for, and back is the letter w already belongs to, or null when the key was new. If either one is not null and differs from w or c, return false. back is a Character object and c a plain char, so back != c compares the two letters as values.
  5. If the loop reaches the end, every position agreed with both maps, so return true.

The main method runs the three examples, then "abc" with "dog cat dog", which needs the second map, "aaa" with "dog dog", where the counts differ, and a single letter with a single word.

Java
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:

Output
true
false
false
false
false
true

Look at the second and third lines. Both are false, for the two different reasons in the picture: in "dog cat cat fish" the letter a would need two words, and in "cat cat cat cat" the word cat would need two letters.

The fourth line, false for "abc" with "dog cat dog", is where wordToLetter earns its place. The letters a and c would both stand for dog, and only the word-to-letter map notices. A version that keeps only letterToWord prints true for this input, and true for Example 3 as well.

The fifth line is false before the loop even starts, because "dog dog" has two words for three letters. The last line, a with dog, is the smallest pattern that holds.

The original implementation, WordPattern.java, is on GitHub.

Complexity

The work is one split of s and one walk over the positions, with two map calls at each.

  • Time: O(n), with n the number of characters in s. split reads each character of s once, and the two putIfAbsent calls at a position hash and compare one word, so over the whole walk each character of s is read a fixed number of times.
  • Space: O(n). The words array and wordToLetter hold the words of s, at most n characters in all, and letterToWord has one entry per different letter.

With single characters in place of words, the same two-way check solves Isomorphic Strings.