Substring Matching Pattern - Problem
Imagine you're building a search engine that needs to handle wildcard patterns. You have a text string s and a pattern p that contains exactly one * character acting as a wildcard.
The * character can be replaced with any sequence of zero or more characters (including an empty string). Your task is to determine if the pattern p can be made to match any substring of s.
Goal: Return true if pattern p can match a substring of s, false otherwise.
Example: If s = "hello world" and p = "wo*d", we can replace * with "rl" to get "world", which is a substring of s.
Input & Output
example_1.py โ Basic Match
$
Input:
s = "hello world", p = "wo*d"
โบ
Output:
true
๐ก Note:
We can replace * with "rl" to get "world", which is a substring of "hello world"
example_2.py โ Empty Replacement
$
Input:
s = "programming", p = "pro*ing"
โบ
Output:
true
๐ก Note:
We can replace * with "gramm" to get "programming", which matches the entire string
example_3.py โ No Match
$
Input:
s = "hello", p = "wor*ld"
โบ
Output:
false
๐ก Note:
Neither "wor" nor "ld" appear in "hello", so no valid substring can be formed
Visualization
Tap to expand
Understanding the Visualization
1
Split the Pattern
Divide pattern at * into prefix and suffix parts
2
Search for Prefix
Find all positions where the prefix appears in the string
3
Check Suffix Placement
For each prefix position, see if suffix can appear later
4
Validate Match
Ensure there's valid spacing between prefix and suffix
Key Takeaway
๐ฏ Key Insight: By splitting the pattern at the wildcard, we can efficiently search for the fixed parts and validate that they can be connected with any middle section.
Time & Space Complexity
Time Complexity
O(nยฒ)
In worst case, we might find many prefix matches and check suffix for each
โ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค s.length โค 104
- 1 โค p.length โค 103
- s contains only lowercase English letters
- p contains only lowercase English letters and exactly one '*' character
- The '*' character cannot be at the start or end of p
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code