Word Pattern

Easy#290two maps

You get a pattern of letters and a string of words split by spaces. Find out whether the string follows the pattern: each letter always stands for the same word, and two different letters never stand for the same word. Our example: the pattern "abab" and "tick tock tick tock" — yes, a is tick and b is tock.

input
pattern: a string of letters; s: words separated by single spaces.
returns
true if s follows pattern: as many words as letters, each letter always stands for the same word, and different letters for different words; otherwise false.
constraints
  • 1 ≤ pattern.length ≤ 300
  • 1 ≤ s.length ≤ 3000
  • pattern: lowercase English letters
  • s: lowercase words, one space between them, none at the ends
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} pattern
 * @param {string} s
 * @return {boolean}
 */
function wordPattern(pattern, s) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more hash map problems

Pattern “Hash map” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.