Word Pattern II - Problem

Given a pattern and a string s, return true if s matches the pattern.

A string s matches a pattern if there is some bijective mapping of single characters to non-empty strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s.

A bijective mapping means that:

  • No two characters map to the same string
  • No character maps to two different strings

Input & Output

Example 1 — Basic Pattern Match
$ Input: pattern = "abab", s = "redblueredblue"
Output: true
💡 Note: One possible mapping: a → 'red', b → 'blue'. This creates 'red' + 'blue' + 'red' + 'blue' = 'redblueredblue'
Example 2 — No Valid Mapping
$ Input: pattern = "aaaa", s = "asdasdasdasd"
Output: true
💡 Note: Pattern 'aaaa' can map a → 'asd' to create 'asd' + 'asd' + 'asd' + 'asd' = 'asdasdasdasd'
Example 3 — Bijection Violation
$ Input: pattern = "abab", s = "asdfhjkl"
Output: true
💡 Note: One possible mapping: a → 'as', b → 'df', which creates 'as' + 'df' + 'as' + 'df' = 'asdfasdf', but this doesn't match 'asdfhjkl'. However, a → 'asd', b → 'fhj' works: 'asd' + 'fhj' + ... No, this is false.

Constraints

  • 1 ≤ pattern.length ≤ 20
  • 1 ≤ s.length ≤ 50
  • pattern contains only lowercase English letters
  • s contains only lowercase English letters

Visualization

Tap to expand
Word Pattern II: Bijective Character to String MappingababPattern: ababredblueredblueString: redblueredbluea → 'red'b → 'blue'Result: true (bijective mapping found)
Understanding the Visualization
1
Input
Pattern 'abab' and string 'redblueredblue'
2
Process
Find bijective mapping: a→'red', b→'blue'
3
Output
Verify: 'red'+'blue'+'red'+'blue' = input string
Key Takeaway
🎯 Key Insight: Use backtracking to systematically explore character-to-substring mappings while maintaining bijection property
Asked in
Google 25 Facebook 20 Amazon 15
28.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen