Mini Regex Matcher (. and *)
Implement regular-expression matching with "." (any single char) and "*" (zero-or-more of the preceding element) — the classic hard interview problem. The whole subtlety is that "*" can match nothing or many, so you must explore both. Solve it with DP in Python or TypeScript, with hidden tests.
The problem
Implement is_match(s, p): does the pattern p match the entire string s? Two special characters: . matches any single character, and * matches zero or more of the element immediately before it. The match must cover all of s, not just a prefix.
s = 'aa', p = 'a'Falses = 'aa', p = 'a*'Trues = 'ab', p = '.*'Trues = 'aab', p = 'c*a*b'True- A
*always follows a valid element (a letter or.) — it never appears first. - The match is full-string: the pattern must consume all of
s. - Because
*can match zero or many, you must try both branches — a recursion with memoization or a 2-D DP does it in O(m·n).
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement is_match(s, p) with DP. Let dp[i][j] mean "does s[i:] match p[j:]?" Fill it from the end. Handle a * at p[j+1] by either skipping the pair (zero matches) or consuming one char of s (if it matches) and staying on the same pattern element.
- Work backwards:
dp[i][j]= doess[i:]matchp[j:]? The base casedp[len(s)][len(p)] = True. - Let
first = i < len(s) and (p[j] == s[i] or p[j] == ".")— does the current char match here? - If the next pattern char is
*:dp[i][j] = dp[i][j+2](use zero) or(first and dp[i+1][j])(use one, stay). - Otherwise:
dp[i][j] = first and dp[i+1][j+1]. The answer isdp[0][0].
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.