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: false
💡 Note: No bijective mapping exists. For example, trying a → 'as', b → 'df' gives 'as' + 'df' + 'as' + 'df' = 'asdfasdf' ≠ 'asdfhjkl'. All other possible mappings also fail to produce the target string.

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 - Backtracking Solution INPUT Pattern: "abab" a b a b String s: "redblueredblue" red blue red blue Bijective Mapping Required: a --> ? b --> ? Each char maps to unique non-empty substring ALGORITHM STEPS 1 Backtrack with Maps Track char->str and str->char 2 Try All Substrings For each pattern char, try all possible substrings 3 Check Consistency If char mapped, verify match If new, check not used 4 Recurse or Backtrack Continue if valid, undo and try next if not Mapping Table Char String a "red" b "blue" FINAL RESULT Pattern Matched! a red b blue Verification: a + b + a + b = red + blue + red + blue = "redblueredblue" Output: true Bijective mapping exists Pattern matches string! Key Insight: Use backtracking with two hash maps to maintain bijective mapping. For each pattern character, try all possible substrings. If the character is already mapped, verify the substring matches. If new, ensure the substring isn't mapped to another character. Time: O(n^m), Space: O(m+n) TutorialsPoint - Word Pattern II | Optimal Backtracking Solution
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