InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Word Pattern

easy Original ↗ 00:00

Problem

You are given a pattern string of lowercase letters and a sentence s of lowercase words separated by single spaces. Determine whether s follows the pattern: there must be a one-to-one correspondence (a bijection) between the letters of pattern and the words of s, such that replacing each letter by its word reproduces the sentence exactly.

The one-to-one requirement holds in both directions: a letter always maps to the same word, and no two different letters map to the same word.

Examples

  • pattern = "abba", s = "dog cat cat dog"True — a↔dog, b↔cat is a consistent bijection.
  • pattern = "abba", s = "dog cat cat fish"Falsea would have to be both “dog” and “fish”.
  • pattern = "abba", s = "dog dog dog dog"False — both a and b would map to “dog”, which breaks one-to-one.

Constraints

  • 1 <= pattern.length <= 300, letters only.
  • 1 <= s.length <= 3000; words are lowercase letters separated by single spaces (no leading/trailing spaces).

The bounds are small, so the mapping logic must be correct; speed is not the constraint here.

Think about it first

Hint 1 Split `s` into words first. If the number of words differs from the number of letters, you can answer immediately.
Hint 2 A dict from letter → word catches "a maps to two different words". What input breaks a solution that has *only* that dict? (Look at example 3.)
Hint 3 Keep two maps — letter → word and word → letter — and walk the pairs in lockstep; any disagreement with an existing entry in either map means `False`. (Equivalently: letter and word must always have matching first-occurrence positions.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug