Taro Logo

Regular Expression Matching

#138 Most AskedHard
Topics:
StringsDynamic ProgrammingRecursion

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 <= 20
  • 1 <= p.length <= 20
  • s contains only lowercase English letters.
  • p contains only lowercase English letters, '.', and '*'.
  • It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.

Solution


Clarifying Questions

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:

  1. What character set should we expect in the input string `s` and pattern `p`? Are they strictly lowercase English letters, or can they include uppercase letters, numbers, or special characters?
  2. Can the pattern `p` start with a `*`, or are we guaranteed that `*` is always preceded by a valid preceding element?
  3. What should be returned if both the input string `s` and the pattern `p` are empty? Should it evaluate to true?
  4. Can the pattern contain consecutive `*` wildcards (e.g., `a**b`), and if so, how should they be handled?
  5. Are there any length constraints on the input string `s` or the pattern `p` that would impact stack depth for recursion or memory allocation for dynamic programming?

Brute Force Solution

Approach

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:

  1. Start at the very beginning of both the secret code and the template.
  2. Compare the first character of the code with the first character of the template.
  3. If the characters match, or if the template has a wildcard that can match anything, move forward to the next pair of characters.
  4. If the template has a special repetition symbol, branch out into multiple parallel paths to try every possible scenario.
  5. For example, try pretending the repetition symbol means using the preceding character zero times, then try one time, then two times, and so on.
  6. Follow each of these different paths independently, making choices step by step as you move forward through the code and the template.
  7. If a path reaches a point where the characters no longer match and no other rules apply, consider that path a dead end and stop following it.
  8. If you successfully reach the very end of both the code and the template at the same time on any of the paths, conclude that the template successfully matches the code.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(2^(T + S)) – The cost is driven by the recursive exploration of branching paths when encountering repetition symbols in the template, where T represents the length of the template and S represents the length of the secret code. At each choice point with an asterisk, the algorithm may branch into multiple parallel paths to try zero or more repetitions. In the worst-case scenario, this leads to an exponential number of states visited as the lengths of the code and template increase. This total exploration across all possible decision branches approximates an exponential growth formula that simplifies to O(2^(T + S)).
Space Complexity
O(M * N) – To eliminate redundant parallel paths and avoid recalculating overlapping subproblems implied by the branching repetition rules, an auxiliary two-dimensional boolean table of size (M plus one) by (N plus one) is required, where M and N represent the lengths of the secret code and the template respectively. In addition to this DP table, the recursive approach or iterative state storage consumes memory proportional to the table dimensions. As the lengths of the code and template grow, this explicitly allocated matrix scales quadratically with the input sizes. Therefore, the total auxiliary space complexity simplifies in Big O notation to O(M * N).

Optimal Solution

Approach

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:

  1. Begin comparing the text and the pattern from their very beginnings, moving forward character by character.
  2. If the characters match directly, or if the pattern has a wildcard that can match any single character, simply move past both of them and continue.
  3. When you encounter a special repeating symbol in the pattern, pause and consider two main possibilities.
  4. The first possibility for the repeating symbol is to pretend it is not there and skip over it along with the character it affects, seeing if the rest of the text still matches.
  5. The second possibility is to use the repeating symbol to match the current character in the text, and then stay on the same pattern piece to see if it can match more characters ahead.
  6. Keep track of the answers to these sub-comparisons as you go so you never waste time solving the exact same overlap twice.
  7. Continue this process until you have either successfully matched the entire text or proven that a match is impossible.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(T * P) – The time complexity is driven by comparing the text of length T and the pattern of length P, where we compute results for every possible index combination of both strings. Because we cache the results of these sub-comparisons to avoid redundant work, each unique state between a text index and pattern index is evaluated at most once. This creates a grid of subproblems where the total operations approximate T * P, which simplifies to O(T * P).
Space Complexity
O(m * n) – To keep track of the answers to the sub-comparisons as you go and avoid solving the exact same overlap twice, the algorithm utilizes a two-dimensional memoization table or dynamic programming grid. If we define m as the length of the text and n as the length of the pattern, this auxiliary table stores boolean results for every possible index combination of the text and pattern. Therefore, the extra memory used scales directly with the product of the input dimensions, resulting in an auxiliary space complexity of O(m * n).

Edge Cases

Both string and pattern are completely empty
How to Handle:
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
How to Handle:
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*
How to Handle:
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
How to Handle:
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**
How to Handle:
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*
How to Handle:
Memoization or dynamic programming ensures states are computed once, avoiding exponential time complexity blowups.
No valid match exists between the string and pattern
How to Handle:
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
How to Handle:
Using bottom-up dynamic programming instead of pure recursion eliminates stack overflow risks and operates within optimal time and space limits.
0/245 completed