CodingNodes / Arrays & Hashing / Word Pattern System design Space play · ←→ step · R restart

Problem

You get a pattern made of letters and a sentence s made of words separated by single spaces.

Return true if the sentence follows the pattern: each letter stands for one word, and each word belongs to one letter. The match must be exact in both directions, with one word per letter.

Constraints

  • 1 ≤ pattern.length ≤ 300
  • pattern uses lowercase English letters
  • s uses lowercase letters and single spaces, with no leading or trailing space

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Splitting and the single pass both take linear time, with O(1) map lookups per index.

Space: The maps and the word list together hold at most n entries each.

Keep a map from letters to words and another from words back to letters. At each index both maps must agree with the current pair. Checking only one direction would let two letters share a word.