ExamAdda Logo

Word Pattern

Easy

Given a pattern and a string s, determine if s follows the same pattern.

A string follows a pattern if there is a one-to-one correspondence between each character in the pattern and each word in the string.

Each character maps to exactly one word, and each word maps to exactly one character.

Example 1

Input

abba
dog cat cat dog

Output

true

Explanation

'a' maps to "dog" and 'b' maps to "cat". The mapping is consistent and one-to-one.

Example 2

Input

abba
dog cat cat fish

Output

false

Explanation

The last word is "fish" instead of "dog", so the pattern is violated.

Constraints

1 ≤ pattern.length ≤ 300
1 ≤ s.length ≤ 3000
pattern consists of lowercase English letters.
s consists of lowercase English letters and spaces.

Hints:

Hint 1

Split the string into words and first check if the number of words matches the length of the pattern.

Hint 2

Use two hash maps: one for character-to-word mapping and another for word-to-character mapping to maintain a one-to-one correspondence.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 6, 2026

Last updated

Aug 7, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output