Skip to content
Problem 290 · LeetCode 290(opens in a new tab)

Word Pattern

EasyHash tables

You are given a string pattern of lower-case letters and a string s of words separated by single spaces. Decide whether s follows the pattern.

It follows the pattern when the letters and words pair up one to one: there is one word per letter, read left to right, every copy of a letter stands for the same word, and two different letters never stand for the same word. Return true or false.

Example 1

Input:  pattern = "abab", s = "sun moon sun moon"
Output: true
Why:    a is always sun, b is always moon
2 more examples and the constraints

Example 2

Input:  pattern = "abab", s = "sun sun sun sun"
Output: false
Why:    a and b would both stand for sun

Example 3

Input:  pattern = "aab", s = "up up"
Output: false
Why:    three letters but only two words

Constraints

  • 1 ≤ length of pattern ≤ 300, lower-case letters only
  • 1 ≤ length of s ≤ 3,000
  • s has lower-case words, one space between each, and no space at either end

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every pairO(n² · w)
  2. Two hash mapsO(n + L)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 300 wordsVerdict
Check every pairO(n² · w)
Mention it, then move on
Two hash mapsO(n + L)
Best; one pass

n = number of letters, w = longest word, L = length of s.

Edge cases to test

  • Counts differ. "aab" with "up up", or "a" with "go go": false before any map is used.
  • Two letters, one word. "abab" with "sun sun sun sun" passes the letter map but fails the word map.
  • One letter, two words. "aa" with "red blue" fails the letter map.
  • Similar words. "car" and "cart" are different words; compare whole words, not prefixes.

Common mistakes

  • Using only the letter-to-word map, so two letters can share one word.
  • Forgetting to compare the counts first, which reads past the end or ignores extra words.
  • Comparing Java strings with == instead of equals.

How to talk through it

  1. 1Clarify. One space between words? Can two letters mean the same word? (No, it must be one to one.)
  2. 2Give the pair check. Same letter must mean same word, for every pair. Say it is O(n²).
  3. 3Name the bijection. One to one needs a check in each direction, so keep two maps.
  4. 4Code the one pass. Compare counts, then check both maps before storing each pair.
  5. 5Test out loud. Run a count mismatch and "abab" with four equal words before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?