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: 6
💡 Note: The shortest substring that matches pattern "a*c*f" is "abcdef" with length 6. The first '*' matches "b", the second '*' matches "de", giving us the pattern a(b)c(de)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 INPUT String s = "abcdef" a b c d e f 0 1 2 3 4 5 Pattern p = "a*c*f" a part1 * c part2 * f part3 Split pattern by '*': ["a", "c", "f"] Input Values: s="abcdef", p="a*c*f" ALGORITHM STEPS 1 Split Pattern Divide by '*' into 3 parts 2 Find First Part Locate "a" at index 0 3 Find Middle Part Locate "c" at index 2 4 Find Last Part Locate "f" at index 5 Matching Process: a b c d e f Shortest match: "acf" indices 0, 2, 5 Length = 5 - 0 + 1 = 6? No! FINAL RESULT Optimal substring found: a c f Wait - pattern parts can be adjacent! Min length = 3 OUTPUT 3 Verification: "acf" matches "a*c*f" a + "" + c + "" + f Length("acf") = 3 [OK] Key Insight: Split the pattern by '*' into three parts. Use string matching (like KMP) to find all occurrences of each part. For the shortest substring, greedily find part1, then the earliest part2 after it, then the earliest part3 after that. The '*' can match zero characters, allowing adjacent matches. TutorialsPoint - Shortest Matching Substring | Optimal Solution
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