AAlgoLoopSpaced repetition for LeetCode
EASYHash Map / SetLeetCode ↗

Word Pattern

The key idea

A valid pattern is a two-way (bijective) mapping: each pattern letter binds to exactly one word AND each word binds to exactly one letter. Track both directions in two hash maps and reject the first time either binding contradicts a previous one.

Problem

You are given a pattern and a string s. Return true if s follows the same pattern.

Here *follow* means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Specifically:

- Each letter in pattern maps to exactly one unique word in s.
- Each unique word in s maps to exactly one letter in pattern.
- No two letters map to the same word, and no two words map to the same letter.

The i-th letter of pattern lines up with the i-th word of s, where the words of s are separated by single spaces.

Constraints

Examples

Input: pattern = "abba", s = "dog cat cat dog" Output: true
Input: pattern = "abba", s = "dog cat cat fish" Output: false
Input: pattern = "aaaa", s = "dog cat cat dog" Output: false

Complexity

Time: O(n + m) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems