Shortest Matching Substring - Problem
Pattern Matching with Wildcards
You're given a string
Your task is to find the shortest substring in
Key Points:
• The pattern has exactly 2 wildcards (*)
• Empty substrings are valid matches
• You need the minimum length matching substring
Example: If
You're given a string
s and a pattern p that contains exactly two '*' characters. Each '*' acts as a wildcard that can match any sequence of zero or more characters.Your task is to find the shortest substring in
s that matches the pattern p. If no such substring exists, return -1.Key Points:
• The pattern has exactly 2 wildcards (*)
• Empty substrings are valid matches
• You need the minimum length matching substring
Example: If
s = "abcdef" and p = "a*f", then "abcdef" matches but "af" would be shorter if it existed. Input & Output
example_1.py — Basic Pattern Match
$
Input:
s = "abcdef", p = "a*f"
›
Output:
6
💡 Note:
The pattern 'a*f' means: starts with 'a', ends with 'f', with anything in between. The shortest substring matching this is "abcdef" with length 6.
example_2.py — Multiple Matches
$
Input:
s = "abacaba", p = "a*a"
›
Output:
3
💡 Note:
Multiple substrings match 'a*a': "aba" (length 3), "abaca" (length 5), "abacaba" (length 7). The shortest is "aba" with length 3.
example_3.py — No Match Found
$
Input:
s = "hello", p = "a*z"
›
Output:
-1
💡 Note:
No substring in "hello" starts with 'a' and ends with 'z', so no match exists.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Landmarks
Split the pattern 'a*b*c' into prefix 'a', middle section, and suffix 'c'
2
Find Starting Points
Locate all positions where the prefix 'a' appears in the string
3
Find Closest Destinations
For each starting point, find the nearest suffix 'c' that comes after it
4
Calculate Shortest Route
Measure the distance from start of prefix to end of suffix, keep the minimum
Key Takeaway
🎯 Key Insight: The shortest matching substring is determined by finding the closest valid prefix-suffix pair. We don't need to check every possible substring - just find optimal anchor points!
Time & Space Complexity
Time Complexity
O(n³)
O(n²) substrings × O(n) pattern matching per substring
⚠ Quadratic Growth
Space Complexity
O(1)
Only storing pattern parts and current substring info
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 104
- 3 ≤ p.length ≤ 100
- p contains exactly two '*' characters
- s and p consist of lowercase English letters and '*'
- The empty substring is considered valid if both prefix and suffix are empty
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code