Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.'*' Matches zero or more of the preceding element.The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab", p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)".
Constraints:
1 <= s.length <= 201 <= p.length <= 20s contains only lowercase English letters.p contains only lowercase English letters, '.', and '*'.'*', there will be a previous valid character to match.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are trying to match a secret code against a template that contains wildcard symbols and repetition rules. The brute force approach involves exploring every single possibility of how the template could match the code from beginning to end.
Here's how the algorithm would work step-by-step:
def is_match(text_string, pattern_string):
def match_helper(text_index, pattern_index):
if pattern_index == len(pattern_string):
return text_index == len(text_string)
# Check if the current characters match directly or if the pattern has a wildcard character
first_match = text_index < len(text_string) and pattern_string[pattern_index] in {text_string[text_index], '.'}
if pattern_index + 1 < len(pattern_string) and pattern_string[pattern_index + 1] == '*':
# Branch into multiple paths to explore zero-occurrence or multi-occurrence of the repeated character
return (match_helper(text_index, pattern_index + 2) or
(first_match and match_helper(text_index + 1, pattern_index)))
else:
# Advance both pointers simultaneously when no repetition rule is present
return first_match and match_helper(text_index + 1, pattern_index + 1)
return match_helper(0, 0)Instead of checking every single possible way to match the pattern to the text, the optimal approach builds the solution step by step by comparing pieces of the text and pattern side by side. It remembers previous answers to avoid repeating the exact same work, ensuring a fast and efficient comparison.
Here's how the algorithm would work step-by-step:
class Solution:
def isMatch(self, input_text: str, match_pattern: str) -> bool:
memoization_cache = {}
def recursive_match(text_index: int, pattern_index: int) -> bool:
# Caching overlapping subproblems prevents exponential time complexity.
if (text_index, pattern_index) in memoization_cache:
return memoization_cache[(text_index, pattern_index)]
if pattern_index == len(match_pattern):
return text_index == len(input_text)
characters_match = text_index < len(input_text) and match_pattern[pattern_index] in {input_text[text_index], '.'}
has_kleene_star = pattern_index + 1 < len(match_pattern) and match_pattern[pattern_index + 1] == '*'
if has_kleene_star:
# Branching explores zero occurrences or consumes the current character.
skip_star_pattern = recursive_match(text_index, pattern_index + 2)
consume_character = characters_match and recursive_match(text_index + 1, pattern_index)
result = skip_star_pattern or consume_character
else:
# Direct matches advance both pointers together to check remaining substrings.
result = characters_match and recursive_match(text_index + 1, pattern_index + 1)
memoization_cache[(text_index, pattern_index)] = result
return result
return recursive_match(0, 0)| Case | How to Handle |
|---|---|
| Both string and pattern are completely empty | The base case in recursion or DP table initializes both empty indices as true since an empty pattern matches an empty string. |
| Pattern is empty but the input string is not empty | The base case will naturally evaluate to false because a non-empty string cannot be matched by an empty pattern. |
| Input string is empty but pattern contains valid star expressions like a*b* | The DP state handles this by allowing zero occurrences of the preceding element through iterative transitions. |
| Pattern consists solely of a dot and a star like .* to match everything | The star logic correctly evaluates that dot matches any single character and star repeats it infinitely to cover the entire string. |
| Consecutive star operators in the pattern such as a** | Most standard problems assume valid regular expression syntax, but sanitizing or handling redundant stars prevents infinite loops in naive recursion. |
| Pattern has alternating characters and stars that match zero elements repeatedly like a*b*c* | Memoization or dynamic programming ensures states are computed once, avoiding exponential time complexity blowups. |
| No valid match exists between the string and pattern | The algorithm processes all combinations and eventually returns false when no state transitions lead to a successful completion. |
| Maximum length strings causing deep recursion stack overflow | Using bottom-up dynamic programming instead of pure recursion eliminates stack overflow risks and operates within optimal time and space limits. |