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
Shortest Matching Substring ProblemInput String:abcdefPattern:a*c*fShortest Match: "acf" (Length 3)Pattern matches with wildcards filling gaps between required characters
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 25
28.5K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen