Shortest Matching Substring - Problem
Pattern Matching with Wildcards

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
Pattern Matching VisualizationString: "abacdefaba" Pattern: "a*a"a b a c d e f a b a0 1 2 3 4 5 6 7 8 9Start: 'a' at pos 0Next 'a' at pos 2 → length 3Next 'a' at pos 7 → length 8Next 'a' at pos 9 → length 10Shortest match: "aba" (length 3)Start: 'a' at pos 2Next 'a' at pos 7 → length 6Next 'a' at pos 9 → length 8
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

n
2n
Quadratic Growth
Space Complexity
O(1)

Only storing pattern parts and current substring info

n
2n
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
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
32.5K Views
Medium-High Frequency
~18 min Avg. Time
1.3K 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