Word Pattern

EasyArrays & Hashingbijection map

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a pattern string and a sentence s, decide whether s follows the same letter pattern. Here, "follows" means there is a **bijection** (a full, two-way, one-to-one mapping) between each character in pattern and each whitespace-separated word in s. Concretely: - Every occurrence of a given character in pattern must map to the same word in s. - Every occurrence of a given word in s must map to the same character in pattern. - No two distinct characters may map to the same word, and no two distinct words may map to the same character. The words in s are separated by single spaces. Return true if s follows pattern, and false otherwise.

Examples

Input: pattern = "abba", s = "dog cat cat dog"
Output: true
The mapping a -> "dog" and b -> "cat" works consistently in both directions.
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
The first 'a' maps to "dog" but the last 'a' would need to map to "fish", which contradicts the earlier mapping.
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Every 'a' must map to the same word, but the words differ, so no valid mapping exists.

Constraints

  • 1 <= pattern.length <= 300
  • pattern contains only lowercase English letters.
  • 1 <= s.length <= 3000
  • s contains only lowercase English letters and single spaces between words.
  • s does not begin or end with a space, and there are no consecutive spaces.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bijection map problems