Code Logo

Word Pattern

Published at24 Jul 2026
Medium 0 views
Like0

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

Example 1
Input
"abba", "dog cat cat dog"
Output
true
Explanation

Bijection holds: a→dog, b→cat.

Example 2
Input
"aaaa", "dog cat cat dog"
Output
false
Explanation

Each a maps to different words.

Example 3
Input
"abba", "dog cat cat fish"
Output
false
Explanation

Last word breaks mapping.

Example 4
Input
"abba", "dog dog dog dog"
Output
false
Explanation

b maps to dog but a already maps to dog.

Example 5
Input
"", ""
Output
true
Explanation

Empty pattern and empty string match.

Algorithm Flow

Recommendation Algorithm Flow for Word Pattern

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.

function wordPattern(pattern, s) {
  var words = s.split(' '), pMap = {}, wMap = {};
  if (pattern.length !== words.length) return false;
  for (var i = 0; i < pattern.length; i++) {
    var p = pattern[i], w = words[i];
    if (pMap[p] && pMap[p] !== w) return false;
    if (wMap[w] && wMap[w] !== p) return false;
    pMap[p] = w; wMap[w] = p;
  }
  return true;
}

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

java
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;
    }
}