Shortest Matching Substring - Problem
You are given a string s and a pattern string p, where p contains exactly two '*' characters. The '*' in p matches any sequence of zero or more characters.
Return the length of the shortest substring in s that matches p. If there is no such substring, return -1.
Note: The empty substring is considered valid.
Input & Output
Example 1 — Basic Pattern Match
$
Input:
s = "abcdef", p = "a*c*f"
›
Output:
3
💡 Note:
The shortest substring that matches pattern "a*c*f" is "acf" (positions 0, 2, 5) with length 3. The first '*' matches empty string between 'a' and 'c', and the second '*' matches empty string between 'c' and 'f'.
Example 2 — Empty String Match
$
Input:
s = "hello", p = "**"
›
Output:
0
💡 Note:
Pattern "**" matches any string including the empty substring. Since empty substring is valid and has length 0, the answer is 0.
Example 3 — No Match Found
$
Input:
s = "abc", p = "a*z*c"
›
Output:
-1
💡 Note:
No substring of "abc" can match pattern "a*z*c" because there's no 'z' character in the string. The pattern requires 'a', then any sequence, then 'z', then any sequence, then 'c'.
Constraints
- 1 ≤ s.length ≤ 1000
- 3 ≤ p.length ≤ 1000
- p contains exactly two '*' characters
- s and p consist of lowercase English letters and '*'
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s and pattern p with exactly two '*' wildcards
2
Process
Find all substrings that match the pattern
3
Output
Return length of shortest matching substring
Key Takeaway
🎯 Key Insight: Decompose the pattern into fixed parts and use efficient algorithms to find the minimum window containing all required elements.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code