Regular Expression Matching - Problem
You're tasked with building a powerful regular expression engine that can handle two special wildcard characters. Given an input string s and a pattern p, determine if the pattern matches the entire input string.
Your regex engine must support:
'.'- Matches any single character (like a joker card)'*'- Matches zero or more of the preceding element
Important: The pattern must match the complete string, not just a substring. For example, pattern "a" does NOT match string "aa" because it doesn't cover the entire input.
Examples:
s = "aa", p = "a*"→true(a* means zero or more 'a's)s = "ab", p = ".*"→true(.* matches any sequence)s = "aab", p = "c*a*b"→true(c* matches 0 c's, a* matches 2 a's, b matches b)
Input & Output
example_1.py — Basic Star Pattern
$
Input:
s = "aa", p = "a*"
›
Output:
true
💡 Note:
The pattern 'a*' means zero or more 'a' characters. Since we have exactly 2 'a's in the string, the pattern matches perfectly.
example_2.py — Wildcard with Star
$
Input:
s = "ab", p = ".*"
›
Output:
true
💡 Note:
The pattern '.*' means zero or more of any character. This universal pattern matches any string, including 'ab'.
example_3.py — Complex Pattern
$
Input:
s = "aab", p = "c*a*b"
›
Output:
true
💡 Note:
Breaking down the pattern: 'c*' matches 0 c's (empty), 'a*' matches 2 a's, and 'b' matches the final 'b'. Together they cover the entire string 'aab'.
Visualization
Tap to expand
Understanding the Visualization
1
Start Investigation
Begin comparing your clues with the evidence from the beginning
2
Use Special Tools
When you encounter '.', it matches any single piece of evidence. When you see '*', you can use the previous clue multiple times
3
Make Choices
For '*' patterns, decide whether to use zero matches or keep using more matches
4
Memoize Results
Remember your findings at each position to avoid re-investigating the same evidence
5
Solve Case
Successfully match all evidence with your clues to solve the case
Key Takeaway
🎯 Key Insight: Regular expression matching is like being a detective - you need to systematically check each piece of evidence against your clues, using memoization to remember what you've already investigated. The '*' wildcard gives you choices (use zero or more), making this a perfect candidate for dynamic programming!
Time & Space Complexity
Time Complexity
O(S × P)
Each (i,j) pair is computed at most once, and there are S×P possible pairs
✓ Linear Growth
Space Complexity
O(S × P)
Memoization table stores results for all string/pattern position combinations
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 20
- 1 ≤ p.length ≤ 30
- s contains only lowercase English letters
-
p contains only lowercase English letters,
'.', and'*' -
Important:
'*'will not be the first character in pattern
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code