Wildcard Matching - Problem
You're building a file search system that needs to match filenames against patterns with wildcards! ๐
Given an input string s and a pattern p, implement wildcard pattern matching with support for:
'?'- Matches exactly one character (like a single letter placeholder)'*'- Matches any sequence of characters, including empty sequence (the ultimate wildcard!)
The matching must cover the entire input string - no partial matches allowed. Think of it like checking if a filename exactly matches a search pattern.
Examples:
s = "adceb", p = "*a*b"โtrue(pattern matches any chars + 'a' + any chars + 'b')s = "adceb", p = "a?c?b"โtrue('a' + any char + 'c' + any char + 'b')s = "cb", p = "?a"โfalse(second char must be 'a', but it's 'b')
Input & Output
example_1.py โ Basic Wildcard Matching
$
Input:
s = "adceb", p = "*a*b"
โบ
Output:
true
๐ก Note:
The first '*' matches the empty sequence, while the second '*' matches "dce". The pattern becomes "" + "a" + "dce" + "b" = "adceb", which matches the input string.
example_2.py โ Question Mark Wildcard
$
Input:
s = "adceb", p = "a?c?b"
โบ
Output:
true
๐ก Note:
The first '?' matches 'd', and the second '?' matches 'e'. The pattern becomes "a" + "d" + "c" + "e" + "b" = "adceb", which exactly matches the input string.
example_3.py โ No Match Case
$
Input:
s = "cb", p = "?a"
โบ
Output:
false
๐ก Note:
The '?' can match 'c', but then we need 'a' to match 'b', which is impossible. There's no way to make the pattern "?a" match the string "cb".
Visualization
Tap to expand
Understanding the Visualization
1
Initialize base cases
Empty string matches empty pattern, handle leading '*' wildcards
2
Character by character
For each position, determine if current characters can match
3
Handle wildcards
'?' matches any single char, '*' matches zero or more chars
4
Build solution
Combine partial matches to determine if entire string matches pattern
Key Takeaway
๐ฏ Key Insight: Dynamic Programming efficiently handles the exponential possibilities of '*' wildcards by storing intermediate results, avoiding repeated computations.
Time & Space Complexity
Time Complexity
O(mรn)
Still need to process every character combination once
โ Linear Growth
Space Complexity
O(n)
Only store two arrays of size n (pattern length)
โก Linearithmic Space
Constraints
- 0 โค s.length, p.length โค 2000
- s contains only lowercase English letters
-
p contains only lowercase English letters,
'?'or'*' - Follow up: Could you improve the space complexity to O(n)?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code