Match a string with wildcard pattern recursively
Company: Citadel
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in string pattern matching, recursive problem decomposition, and algorithmic optimization including handling wildcard semantics and complexity analysis.
Constraints
- 0 <= len(s), len(p) <= 2000
- s and p consist of printable characters, where p may also contain '?' and '*'
- The solution should avoid exponential recursion by caching repeated states
Examples
Input: ("aa", "a")
Expected Output: False
Explanation: The pattern 'a' matches only one character, so it cannot match the entire string 'aa'.
Input: ("aa", "*")
Expected Output: True
Explanation: The '*' wildcard can match any sequence, including 'aa'.
Input: ("cb", "?a")
Expected Output: False
Explanation: '?' matches 'c', but then 'a' does not match 'b'.
Input: ("adceb", "*a*b")
Expected Output: True
Explanation: The first '*' can match an empty prefix, the second '*' can match 'dce', and the remaining letters align.
Input: ("", "")
Expected Output: True
Explanation: An empty pattern matches an empty string.
Input: ("", "*")
Expected Output: True
Explanation: The '*' wildcard can match the empty sequence.
Input: ("", "?")
Expected Output: False
Explanation: '?' must match exactly one character, but the string is empty.
Input: ("abcde", "a*?e")
Expected Output: True
Explanation: 'a' matches 'a', '*' can match 'bc', '?' matches 'd', and 'e' matches 'e'.
Input: ("abc", "a**c")
Expected Output: True
Explanation: Consecutive '*' characters still behave like a wildcard sequence matcher, so this matches 'abc'.
Input: ("acdcb", "a*c?b")
Expected Output: False
Explanation: No way of expanding '*' makes the rest of the pattern match the entire string.
Hints
- Think of each recursive state as a pair of indices: one in the string and one in the pattern.
- If you memoize the answer for each (i, j), you can avoid recomputing the same wildcard decisions many times.