Word Pattern solution explained

To check whether a sentence follows a letter pattern, split it into words, confirm the word count equals the pattern length, then walk both together with two dictionaries: letter to word and word to letter. If either dictionary already holds a different partner for the current pair, the answer is false. Two maps are needed because the match must work in both directions. It runs in O(n) time over the total input size.

By Published 6 min read

The task, restated

You get a pattern made of lowercase letters and a sentence of lowercase words separated by single spaces. The sentence follows the pattern if you can assign each letter one word so that reading the pattern letter by letter spells out the sentence, and no two different letters share the same word. Return true or false.

Examples made up for this walkthrough
PatternSentenceFollows?Why
xyzxred blue gold redYesx is red, y is blue, z is gold, consistently
xyxyred blue red greenNoy would need to be both blue and green
xxxxsun sun sun sunYesOne letter, one word
xysun sunNoTwo letters cannot share one word
xyzmoon starNoThree letters, two words
Examples made up for this walkthrough. Scroll sideways on a small screen.

Worth confirming: can the sentence have extra spaces, and are the words case sensitive? The common version promises single spaces and lowercase, but asking shows you think about input before code.

What the interviewer is checking

Word Pattern is an easy question, often a warm-up, and its trap is the second direction. Many first attempts map letters to words and stop, which wrongly accepts xy with sun sun. The interviewer wants to see you test that case, explain why one map is not enough, and choose a clean way to enforce both directions. Using the right map type in JavaScript is a small bonus point.

Brute force: compare every pair of positions

The sentence follows the pattern exactly when, for every pair of positions i and j, the letters match if and only if the words match. Checking all pairs is O(k²) comparisons for k words, each comparison costing up to the word length. It is slow but almost impossible to get wrong, which makes it a good test reference.

def follows_pattern_pairs(pattern, sentence):
    words = sentence.split(" ")
    if len(words) != len(pattern):
        return False
    for i in range(len(words)):
        for j in range(i + 1, len(words)):
            if (pattern[i] == pattern[j]) != (words[i] == words[j]):
                return False
    return True
All pairs, O(k²) comparisons.

Optimal: two dictionaries in one pass

Walk the letters and words together. Keep word_for, mapping a letter to the word it stands for, and letter_for, mapping a word back to its letter. For each pair, if the letter already has a word and it is a different word, fail. If the word already has a letter and it is a different letter, fail. Otherwise record both directions and continue.

def follows_pattern(pattern, sentence):
    words = sentence.split(" ")
    if len(words) != len(pattern):
        return False
    word_for = {}
    letter_for = {}
    for letter, word in zip(pattern, words):
        if word_for.get(letter, word) != word:
            return False
        if letter_for.get(word, letter) != letter:
            return False
        word_for[letter] = word
        letter_for[word] = letter
    return True
Python: two dictionaries, O(n) time over the input size.
function followsPattern(pattern, sentence) {
  const words = sentence.split(" ");
  if (words.length !== pattern.length) return false;
  const wordFor = new Map();
  const letterFor = new Map();
  for (let i = 0; i < words.length; i++) {
    const letter = pattern[i];
    const word = words[i];
    if (wordFor.has(letter) && wordFor.get(letter) !== word) return false;
    if (letterFor.has(word) && letterFor.get(word) !== letter) return false;
    wordFor.set(letter, word);
    letterFor.set(word, letter);
  }
  return true;
}
JavaScript: Map rather than a plain object for the word side.

Why Map in JavaScript? A plain object inherits keys such as constructor and toString. If the sentence contains the word constructor, a lookup on {} finds a function and the comparison goes wrong. Map has no inherited keys, so any word is safe.

A neat alternative records where each letter and each word first appeared. Two sequences follow the same pattern exactly when those first-seen positions line up at every step. It is the same idea in one structure per side, and it generalizes to comparing many sentences at once.

Cost of each approach

k is the number of words, n the total length of the input
ApproachTimeExtra space
All pairs of positionsO(k²) comparisonsO(n) for the split words
Two dictionariesO(n)O(n)
One dictionary plus a set of used wordsO(n)O(n)
First-seen positionsO(n)O(n)
k is the number of words, n the total length of the input. Scroll sideways on a small screen.

Edge cases to test

  • Word count different from pattern length, in either direction.
  • Two letters mapped to the same word: xy with sun sun.
  • One letter mapped to two words: xx with sun moon.
  • A single letter and a single word: true.
  • A word that is also a JavaScript object key, such as constructor.
  • A word that happens to equal one of the pattern letters, such as x y for pattern yx, which is still a valid match.

Common mistakes

  • Checking only letter to word, so different letters can share a word.
  • Skipping the length check and letting zip silently stop at the shorter input.
  • Using a plain JavaScript object as a dictionary keyed by arbitrary words.
  • Comparing sets of letters and words, which ignores order.
  • Splitting on any whitespace when the interviewer said single spaces, or the reverse.

How to explain it out loud

Fictional example

Catching the second direction early
Candidate
First I split the sentence and compare the word count with the pattern length. If they differ, it is false.
Candidate
A map from letter to word is not enough. With pattern x y and sentence sun sun, both letters would map to sun without a conflict. So I also keep a map from word back to letter.
Candidate
One pass, checking both maps at each step. That is linear in the input size, with linear extra space for the maps.

Isomorphic Strings is the same one-to-one check with single characters on both sides, and it is a good place to practice the first-seen-position version. Candy is another problem where a rule must hold in two directions. Group Anagrams uses a signature as a dictionary key, an idea that also fits pattern matching. All walkthroughs are on the coding problems hub.

Practicing with Natively

Warm-ups are short, so the explanation carries most of the signal. When you rehearse on Mac or Windows, Natively transcribes your mock round, which makes it easy to see whether you said the two-direction point aloud. It can also read the problem from a screenshot and draft an approach to compare against yours after you finish. The coding interview page explains these features.

Questions people ask

How do you solve Word Pattern?

Split the sentence, check that the word count equals the pattern length, then walk both with two dictionaries, letter to word and word to letter. Return false on any conflict.

Why do you need two maps in Word Pattern?

The match must be one-to-one. With only a letter-to-word map, two different letters could both map to the same word without any conflict being detected.

What is the time complexity of Word Pattern?

O(n) in the total length of the pattern and sentence, with O(n) extra space for the split words and the maps.

Why use Map instead of an object in JavaScript?

Plain objects inherit keys such as constructor, so a word like that can collide with an inherited property. Map has no inherited keys.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP