Word Pattern II

MediumBacktrackingbacktracking

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

You are given a pattern of letters and a string s. Decide whether you can assign every distinct letter in pattern its own **non-empty** substring so that replacing each letter of pattern with its substring spells out exactly s. The assignment must be a bijection: the same letter always maps to the same substring, and two different letters never map to the same substring. Return true if such an assignment exists, otherwise false.

Examples

Input: pattern = "abab", s = "redblueredblue"
Output: true
`a` -> "red", `b` -> "blue" gives "red"+"blue"+"red"+"blue".
Input: pattern = "aaaa", s = "asdasdasdasd"
Output: true
`a` -> "asd", repeated four times.
Input: pattern = "aabb", s = "xyzabcxzyabc"
Output: false
No split into four pieces makes the first two pieces equal and the last two pieces equal.

Constraints

  • `1 <= pattern.length, s.length <= 20`
  • `pattern` and `s` contain only lowercase English letters

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 backtracking problems