Taro Logo

Regular Expression Matching

Hard
Asked by:
Google
Amazon
Microsoft
Meta
637 views
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

Match the whole text against the pattern by recursion. A dot matches any one character. When the next pattern character is a star, try the preceding element zero times, or use it once and try that same star against the rest of the text.

Here's how the algorithm would work step-by-step:

  1. If the pattern is finished, the match succeeds only when the text is finished too.
  2. The current pattern character matches the current text character when they are equal or the pattern character is a dot.
  3. If the following pattern character is a star, succeed if skipping the two pattern characters works, or if the current character matches and the same star still matches the remaining text.
  4. Otherwise the current characters must match, and the rest of the text must match the rest of the pattern.

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^(s+p)) – A star makes two recursive calls: one skips it, and one consumes a matching text character and keeps the star. Each call moves forward in the text or the pattern. In the worst case the number of calls is O(2^(s+p)), where s is the text length and p is the pattern length.
Space Complexity
O(s+p) – The recursion stores one frame per call, and a single path advances through the text and the pattern, so the stack is O(s+p). The function does not allocate a match table.

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.