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 <= 2000s contains only lowercase English letters.p contains only lowercase English letters, '?' or '*'.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 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:
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)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:
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)| Case | How to Handle |
|---|---|
| Both input string and pattern are empty | 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 | 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 | 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 | 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 | An optimized iterative approach or memoized dynamic programming table prevents exponential time complexity and stack overflow. |
| Pattern contains multiple consecutive asterisks | 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 | The algorithm exhausts all valid state transitions and safely returns false. |
| Maximum sized strings causing memory limits in standard two-dimensional dynamic programming tables | We optimize space complexity to O(n) using only the previous and current rows of the DP table. |