Taro Logo

Wildcard Matching

#162 Most AskedHard
0 views
Topics:
StringsDynamic Programming

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

  • '?' Matches any single character.
  • '*' Matches any sequence of characters (including the empty sequence).

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 = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Constraints:

  • 0 <= s.length, p.length <= 2000
  • s contains only lowercase English letters.
  • p contains only lowercase English letters, '?' or '*'.

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 does the input string `s` and pattern `p` contain? Are we restricted to lowercase English letters, or can they include uppercase letters, digits, or special characters?
  2. Can either the input string `s` or the pattern `p` be empty, and if so, what should be the expected output?
  3. How should consecutive wildcard characters like `*` in the pattern be handled (e.g., does `a**b` behave the same as `a*b`)?
  4. Are there any length constraints on the string `s` and pattern `p` that would dictate whether an $O(n imes m)$ dynamic programming approach is sufficient, or should we anticipate extremely large inputs?
  5. Is the match case-sensitive, meaning does an uppercase letter match its lowercase counterpart?

Brute Force Solution

Approach

Imagine you have a template with special mystery symbols and a real word, and you want to see if the template can spell out that exact word. The brute force approach tries every single possible way the template could match the word, exploring every path until it either finds a success or exhausts all options.

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

  1. Begin at the very start of the template and the very start of the word.
  2. Compare the current symbol from the template with the current letter from the word.
  3. If you hit a standard letter, check if it matches the word letter; if it does, move forward together, and if not, this specific path fails.
  4. If you hit a question mark, treat it as a successful match for any single word letter, then move both forward.
  5. If you hit a star symbol, realize it can represent anything, meaning it could stand for zero letters, one letter, two letters, and so on.
  6. Explore all those branching possibilities for the star by trying every possible length it could cover.
  7. Keep following every single path of choices simultaneously, branching out whenever a star appears.
  8. If any single path successfully reaches the end of both the template and the word at the exact same time, declare a match.
  9. If every single path leads to a dead end without matching everything, conclude that the template does not match the word.

Code Implementation

def is_match(template, word):
    def evaluate_path(template_index, word_index):
        # Base case: if we consume both strings entirely, we found a successful match
        if template_index == len(template) and word_index == len(word):
            return True

        if template_index == len(template):
            return False

        current_template_char = template[template_index]

        if current_template_char == '*':
            # Branching out star possibilities since it can match empty or any sequence
            for next_word_index in range(word_index, len(word) + 1):
                if evaluate_path(template_index + 1, next_word_index):
                    return True
            return evaluate_path(template_index + 1, word_index)

        # Standard character or question mark requires remaining word to exist
        if word_index < len(word):
            current_word_char = word[word_index]
            if current_template_char == '?' or current_template_char == current_word_char:
                return evaluate_path(template_index + 1, word_index + 1)

        return False

    return evaluate_path(0, 0)

Big(O) Analysis

Time Complexity
O(2^(n + m)) – The brute force approach explores every branching possibility when encountering a star symbol, which can represent any length of characters in the word. Because a star forces the algorithm to branch into multiple recursive paths for zero, one, or more characters, the number of explored paths grows exponentially with the length of the template (n) and the word (m). In the worst-case scenario with multiple stars, this branching mimics a binary or higher-order tree of height n + m. Summing the total operations across all exponential branching paths yields a time complexity proportional to 2^(n + m), which simplifies to O(2^(n + m)).
Space Complexity
O(m * n) – To prevent redundant branching and remember paths explored by stars and question marks, an auxiliary 2D boolean lookup table of size (s.length + 1) by (p.length + 1) is allocated. Defining N as the combined length of the string and pattern, this table requires auxiliary space proportional to the product of their lengths. Consequently, the space complexity simplifies to O(m * n) or O(N squared) in the worst-case scenario where m and n are proportional to N.

Optimal Solution

Approach

Instead of checking every single possible way to match the pattern against the text, the optimal approach compares them step by step from left to right. It uses a clever memory technique to keep track of successful matches so far, allowing it to handle wildcards smoothly without getting overwhelmed by combinations.

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

  1. Begin comparing the text and the pattern from their very first characters.
  2. If the characters match or if the pattern has a question mark, simply move forward in both the text and the pattern because that part is successfully handled.
  3. If you encounter a star in the pattern, remember its location and also remember the current spot you are at in the text, then try moving forward in the pattern while keeping the text still.
  4. If things stop matching after a star, use your memory of where the star was to try stretching the star to cover one more character in the text.
  5. Keep repeating this process of matching normal characters, advancing past question marks, and stretching stars until you reach the end of both the text and the pattern.
  6. If you successfully reach the end of both and everything lined up according to the rules, then the pattern matches the text.

Code Implementation

def is_match(string_text, pattern_string):    text_pointer = 0
    pattern_pointer = 0
    star_index = -1
    match_pointer = 0

    # We advance both pointers when characters match or when the pattern contains a question mark.    while text_pointer < len(string_text):        if pattern_pointer < len(pattern_string) and (pattern_string[pattern_pointer] == '?' or pattern_string[pattern_pointer] == string_text[text_pointer]):            text_pointer += 1
            pattern_pointer += 1
        elif pattern_pointer < len(pattern_string) and pattern_string[pattern_pointer] == '*':            # When we encounter a star, we record its position and our current position in the text to potentially backtrack later.            star_index = pattern_pointer
            match_pointer = text_pointer
            pattern_pointer += 1
        elif star_index != -1:
            # If characters mismatch and we previously saw a star, we backtrack the pattern and stretch the star's coverage over the text.            pattern_pointer = star_index + 1
            match_pointer += 1
            text_pointer = match_pointer
        else:
            return False

    # Any remaining characters in the pattern must all be stars to allow a successful match at the end.    while pattern_pointer < len(pattern_string) and pattern_string[pattern_pointer] == '*':        pattern_pointer += 1

    return pattern_pointer == len(pattern_string)

Big(O) Analysis

Time Complexity
O(S * P) – The time complexity is driven by the length of the text string, let us call it S, and the length of the pattern string, let us call it P. As we iterate through both strings, encountering regular characters and question marks takes linear time relative to the text length. When a star is encountered, the algorithm records its position and repeatedly advances through the text up to S times for each of the P pattern characters. This worst-case scenario means the total operations approximate S * P checks across the matrix of possibilities, which simplifies in Big O notation to O(S * P).
Space Complexity
O(1) – The algorithm relies solely on a few primitive pointers and integer variables to track the current positions in the text and pattern, along with the remembered indices for the most recent star and its corresponding text match location. Because these few tracking variables require constant memory regardless of the input sizes, no extra data structures scale with the input. Therefore, the auxiliary space complexity remains strictly constant.

Edge Cases

Both input string and pattern are empty
How to Handle:
The dynamic programming or recursive base case correctly evaluates this as true because an empty pattern matches an empty string.
Pattern contains only consecutive asterisk characters
How to Handle:
The algorithm iterates through the pattern and updates the matching state to allow the asterisks to match an empty sequence of any length.
Pattern is empty while the input string is not empty
How to Handle:
The solution checks boundary conditions and returns false because an empty pattern cannot match a non-empty string.
Input string is empty while pattern contains non-asterisk characters
How to Handle:
The algorithm ensures that any remaining non-asterisk characters in the pattern result in a false match.
Pattern consists of a single asterisk matching a very long input string
How to Handle:
An optimized iterative approach or memoized dynamic programming table prevents exponential time complexity and stack overflow.
Pattern contains multiple consecutive asterisks
How to Handle:
The logic collapses consecutive asterisks into a single wildcard state since multiple stars behave identically to one.
No valid match exists between string and pattern
How to Handle:
The algorithm exhausts all valid state transitions and safely returns false.
Maximum sized strings causing memory limits in standard two-dimensional dynamic programming tables
How to Handle:
We optimize space complexity to O(n) using only the previous and current rows of the DP table.
0/257 completed