Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers · Binary Search · String Matching
Example 1
"abaacbaecebce"
"ba*c*ce"
Example 2
"baccbaadbc"
"cc*baa*adb"
Example 3
"a"
"**"
Step 02
Core Insight
What unlocks the optimal approach
The pattern string <code>p</code> can be divided into three segments.
Use the KMP algorithm to locate all occurrences of each segment in <code>s</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3455: Shortest Matching Substring
class Solution {
public int shortestMatchingSubstring(String s, String p) {
final String[] parts = split(p);
final String a = parts[0];
final String b = parts[1];
final String c = parts[2];
final int ns = s.length();
final int na = a.length();
final int nb = b.length();
final int nc = c.length();
int[] lpsA = getLPS(a + "#" + s);
int[] lpsB = getLPS(b + "#" + s);
int[] lpsC = getLPS(c + "#" + s);
int ans = Integer.MAX_VALUE;
for (int i = 0, j = 0, k = 0; i + nb + nc < ns; ++i) {
while (i < ns && lpsA[na + 1 + i] != na)
++i;
while (j < ns && (j < i + nb || lpsB[nb + 1 + j] != nb))
++j;
while (k < ns && (k < j + nc || lpsC[nc + 1 + k] != nc))
++k;
if (k == ns)
break;
ans = Math.min(ans, k - i + na);
}
return ans == Integer.MAX_VALUE ? -1 : ans;
}
// Returns the lps array, where lps[i] is the length of the longest prefix of
// pattern[0..i] which is also a suffix of this substring.
private int[] getLPS(String pattern) {
int[] lps = new int[pattern.length()];
for (int i = 1, j = 0; i < pattern.length(); ++i) {
while (j > 0 && pattern.charAt(j) != pattern.charAt(i))
j = lps[j - 1];
if (pattern.charAt(i) == pattern.charAt(j))
lps[i] = ++j;
}
return lps;
}
private String[] split(final String p) {
final int i = p.indexOf('*');
final int j = p.indexOf('*', i + 1);
return new String[] {p.substring(0, i), p.substring(i + 1, j), p.substring(j + 1)};
}
}
// Accepted solution for LeetCode #3455: Shortest Matching Substring
package main
import (
"math"
"strings"
)
// https://space.bilibili.com/206214
// 计算字符串 p 的 pi 数组
func calcPi(p string) []int {
pi := make([]int, len(p))
match := 0
for i := 1; i < len(pi); i++ {
v := p[i]
for match > 0 && p[match] != v {
match = pi[match-1]
}
if p[match] == v {
match++
}
pi[i] = match
}
return pi
}
// 在文本串 s 中查找模式串 p,返回所有成功匹配的位置(p[0] 在 s 中的下标)
func kmpSearch(s, p string) (pos []int) {
if p == "" {
// s 的所有位置都能匹配空串,包括 len(s)
pos = make([]int, len(s)+1)
for i := range pos {
pos[i] = i
}
return
}
pi := calcPi(p)
match := 0
for i := range s {
v := s[i]
for match > 0 && p[match] != v {
match = pi[match-1]
}
if p[match] == v {
match++
}
if match == len(p) {
pos = append(pos, i-len(p)+1)
match = pi[match-1]
}
}
return
}
func shortestMatchingSubstring(s, p string) int {
sp := strings.Split(p, "*")
p1, p2, p3 := sp[0], sp[1], sp[2]
// 三段各自在 s 中的所有匹配位置
pos1 := kmpSearch(s, p1)
pos2 := kmpSearch(s, p2)
pos3 := kmpSearch(s, p3)
ans := math.MaxInt
i, k := 0, 0
// 枚举中间(第二段),维护最近的左右(第一段和第三段)
for _, j := range pos2 {
// 右边找离 j 最近的子串(但不能重叠)
for k < len(pos3) && pos3[k] < j+len(p2) {
k++
}
if k == len(pos3) { // 右边没有
break
}
// 左边找离 j 最近的子串(但不能重叠)
for i < len(pos1) && pos1[i] <= j-len(p1) {
i++
}
// 循环结束后,posL[i-1] 是左边离 j 最近的子串下标(首字母在 s 中的下标)
if i > 0 {
ans = min(ans, pos3[k]+len(p3)-pos1[i-1])
}
}
if ans == math.MaxInt {
return -1
}
return ans
}
# Accepted solution for LeetCode #3455: Shortest Matching Substring
class Solution:
def shortestMatchingSubstring(self, s: str, p: str) -> int:
n = len(s)
a, b, c = p.split('*')
lpsA = self._getLPS(a + '#' + s)[len(a) + 1:]
lpsB = self._getLPS(b + '#' + s)[len(b) + 1:]
lpsC = self._getLPS(c + '#' + s)[len(c) + 1:]
ans = math.inf
i = 0 # lpsA's index
j = 0 # lpsB's index
k = 0 # lpsC's index
while i + len(b) + len(c) < n:
while i < n and lpsA[i] != len(a):
i += 1
while j < n and (j < i + len(b) or lpsB[j] != len(b)):
j += 1
while k < n and (k < j + len(c) or lpsC[k] != len(c)):
k += 1
if k == n:
break
ans = min(ans, k - i + len(a))
i += 1
return -1 if ans == math.inf else ans
def _getLPS(self, pattern: str) -> list[int]:
"""
Returns the lps array, where lps[i] is the length of the longest prefix of
pattern[0..i] which is also a suffix of this substring.
"""
lps = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
while j > 0 and pattern[j] != pattern[i]:
j = lps[j - 1]
if pattern[i] == pattern[j]:
lps[i] = j + 1
j += 1
return lps
// Accepted solution for LeetCode #3455: Shortest Matching Substring
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3455: Shortest Matching Substring
// class Solution {
// public int shortestMatchingSubstring(String s, String p) {
// final String[] parts = split(p);
// final String a = parts[0];
// final String b = parts[1];
// final String c = parts[2];
// final int ns = s.length();
// final int na = a.length();
// final int nb = b.length();
// final int nc = c.length();
// int[] lpsA = getLPS(a + "#" + s);
// int[] lpsB = getLPS(b + "#" + s);
// int[] lpsC = getLPS(c + "#" + s);
// int ans = Integer.MAX_VALUE;
//
// for (int i = 0, j = 0, k = 0; i + nb + nc < ns; ++i) {
// while (i < ns && lpsA[na + 1 + i] != na)
// ++i;
// while (j < ns && (j < i + nb || lpsB[nb + 1 + j] != nb))
// ++j;
// while (k < ns && (k < j + nc || lpsC[nc + 1 + k] != nc))
// ++k;
// if (k == ns)
// break;
// ans = Math.min(ans, k - i + na);
// }
//
// return ans == Integer.MAX_VALUE ? -1 : ans;
// }
//
// // Returns the lps array, where lps[i] is the length of the longest prefix of
// // pattern[0..i] which is also a suffix of this substring.
// private int[] getLPS(String pattern) {
// int[] lps = new int[pattern.length()];
// for (int i = 1, j = 0; i < pattern.length(); ++i) {
// while (j > 0 && pattern.charAt(j) != pattern.charAt(i))
// j = lps[j - 1];
// if (pattern.charAt(i) == pattern.charAt(j))
// lps[i] = ++j;
// }
// return lps;
// }
//
// private String[] split(final String p) {
// final int i = p.indexOf('*');
// final int j = p.indexOf('*', i + 1);
// return new String[] {p.substring(0, i), p.substring(i + 1, j), p.substring(j + 1)};
// }
// }
// Accepted solution for LeetCode #3455: Shortest Matching Substring
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3455: Shortest Matching Substring
// class Solution {
// public int shortestMatchingSubstring(String s, String p) {
// final String[] parts = split(p);
// final String a = parts[0];
// final String b = parts[1];
// final String c = parts[2];
// final int ns = s.length();
// final int na = a.length();
// final int nb = b.length();
// final int nc = c.length();
// int[] lpsA = getLPS(a + "#" + s);
// int[] lpsB = getLPS(b + "#" + s);
// int[] lpsC = getLPS(c + "#" + s);
// int ans = Integer.MAX_VALUE;
//
// for (int i = 0, j = 0, k = 0; i + nb + nc < ns; ++i) {
// while (i < ns && lpsA[na + 1 + i] != na)
// ++i;
// while (j < ns && (j < i + nb || lpsB[nb + 1 + j] != nb))
// ++j;
// while (k < ns && (k < j + nc || lpsC[nc + 1 + k] != nc))
// ++k;
// if (k == ns)
// break;
// ans = Math.min(ans, k - i + na);
// }
//
// return ans == Integer.MAX_VALUE ? -1 : ans;
// }
//
// // Returns the lps array, where lps[i] is the length of the longest prefix of
// // pattern[0..i] which is also a suffix of this substring.
// private int[] getLPS(String pattern) {
// int[] lps = new int[pattern.length()];
// for (int i = 1, j = 0; i < pattern.length(); ++i) {
// while (j > 0 && pattern.charAt(j) != pattern.charAt(i))
// j = lps[j - 1];
// if (pattern.charAt(i) == pattern.charAt(j))
// lps[i] = ++j;
// }
// return lps;
// }
//
// private String[] split(final String p) {
// final int i = p.indexOf('*');
// final int j = p.indexOf('*', i + 1);
// return new String[] {p.substring(0, i), p.substring(i + 1, j), p.substring(j + 1)};
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Boundary update without `+1` / `-1`
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.