Word Pattern

Easy · Arrays & Hashing · Hash Table · String

Problem

You are given a string pattern of lowercase letters and a string s of words separated by single spaces. s follows pattern when there is a bijection between the letters of the pattern and the words of s:

Return true if s follows pattern, and false otherwise.

Examples

Input: pattern = "xyyx", s = "red blue blue red"
Output: true

x ↔ red and y ↔ blue is a bijection.

Input: pattern = "xy", s = "go go"
Output: false

Two different letters cannot both stand for "go".

Input: pattern = "aaa", s = "sun sun"
Output: false

The pattern has three letters but s has only two words.

Constraints

Approaches

Follow-up

What if s had no spaces, so you had to decide where each word ends? Then you have to guess each new letter’s word and backtrack; the two maps are what prune the guesses (see the use case “The same pattern, with the spaces removed”).

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…