Skip to main content
Back to problems
Leetcode
Medium
Hash Maps
Strings
Google
Word Pattern

Determine whether a pattern string can be matched to words in a sentence with a one-to-one mapping.

Acceptance 0%
Problem Statement

Given a pattern consisting of lowercase letters and a sentence made of space-separated words, determine whether the sentence follows the same pattern.

A valid match means each pattern character maps to exactly one word, and each word maps back to exactly one pattern character. In other words, the mapping must be a bijection.

Input Format

  • A string pattern
  • A string s containing words separated by single spaces

Output Format

  • Return true if s follows pattern
  • Otherwise return false

Constraints

  • 1 <= pattern.length <= 300
  • pattern contains only lowercase English letters
  • 1 <= s.length <= 3000
  • s contains lowercase English letters and single spaces
  • Words are separated by exactly one space
Examples
Sample cases returned by the problem API.

Example 1

Input

pattern = "abba"
s = "dog cat cat dog"

Output

true

Explanation

a -> dog and b -> cat forms a consistent one-to-one mapping.

Example 2

Input

pattern = "abba"
s = "dog cat cat fish"

Output

false

Explanation

The last character a would need to map to both dog and fish, which is not allowed.

Show 1 more example

Example 3

Input

pattern = "aaaa"
s = "dog cat cat dog"

Output

false

Explanation

The single character a would have to map to multiple different words.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.