Word Pattern II — LeetCode 291 Python Solution

MediumLeetCode PremiumHash TableStringBacktracking
Problem
#291
Reading time
5 min

The 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.

Example

Input
pattern = "abab", s = "redblueredblue"
Output
true
Explanation
One possible mapping is as follows:

Python solution

Python
class Solution:
    def wordPatternMatch(self, pattern: str, s: str) -> bool:
        def dfs(i, j):
            if i == m and j == n:
                return True
            if i == m or j == n or n - j < m - i:
                return False
            for k in range(j, n):
                t = s[j : k + 1]
                if d.get(pattern[i]) == t:
                    if dfs(i + 1, k + 1):
                        return True
                if pattern[i] not in d and t not in vis:
                    d[pattern[i]] = t
                    vis.add(t)
                    if dfs(i + 1, k + 1):
                        return True
                    d.pop(pattern[i])
                    vis.remove(t)
            return False

        m, n = len(pattern), len(s)
        d = {}
        vis = set()
        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 291. Word Pattern II is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 291. Word Pattern II?
LeetCode 291. Word Pattern II is rated Medium on LeetCode.
What is the time complexity of LeetCode 291. Word Pattern II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 291. Word Pattern II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 291. Word Pattern II cover?
LeetCode 291. Word Pattern II is tagged Hash Table, String and Backtracking on LeetCode.
Is LeetCode 291. Word Pattern II a premium problem?
Yes. LeetCode 291. Word Pattern II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview