#3455

Shortest Matching Substring

Hard
Two PointersStringBinary SearchString MatchingKMP AlgorithmTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Split the pattern into three parts around the '*' characters. Use KMP to find occurrences of the first and last parts, then check the middle part for minimal matching.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split pattern `p` into three parts: `pre`, `mid`, `post` based on '*' positions.
  2. 2Step 2: Use KMP to find all starting indices of `pre` in `s` and all ending indices of `post` in `s`.
  3. 3Step 3: For each combination of start and end indices, check if `mid` can fit between them and update the minimum length.
solution.py14 lines
1def shortest_matching_substring(s, p):
2    pre, mid, post = p.split('*')
3    starts = kmp_search(s, pre)
4    ends = kmp_search(s, post)
5    min_length = float('inf')
6    for start in starts:
7        for end in ends:
8            if start < end:
9                min_length = min(min_length, end - start + len(pre) + len(post))
10    return min_length if min_length != float('inf') else -1
11
12def kmp_search(s, pattern):
13    # KMP implementation to find occurrences
14    return []

Complexity note: KMP allows us to find occurrences efficiently, leading to O(n) time complexity. Space complexity is O(n) due to storing indices.

  • 1Understanding the role of '*' in pattern matching is crucial.
  • 2Using efficient searching algorithms like KMP can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.