
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗def min_window_subsequence(S: str, T: str) -> str:
n, m = len(S), len(T)
min_len = float('inf')
start = 0
i = 0
while i < n:
if S[i] == T[0]:
t_idx = 0
j = i
# Forward match to find subsequence
while j < n and t_idx < m:
if S[j] == T[t_idx]:
t_idx += 1
j += 1
if t_idx == m: # Full match found
end = j - 1
# Backward shrink to find minimal start
t_idx = m - 1
k = end
while k >= i:
if S[k] == T[t_idx]:
t_idx -= 1
if t_idx < 0:
break
k -= 1
window_len = end - k + 1
if window_len < min_len:
min_len = window_len
start = k
i = k # Move i to start of found window
i += 1
return S[start:start+min_len] if min_len != float('inf') else ""
# Example usage
S = "abcdebdde"
T = "bde"
print(min_window_subsequence(S, T)) # Output: "bcde"| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n * m) | In the best case, for each character in S, we may have to scan up to all characters in T (size m). Even if we find a match early, we still potentially do m comparisons per n characters in S. |
| Average Case | O(n * m) | On average, the algorithm needs to traverse the string S and, for each starting match, walk through T (size m) and then potentially backtrack to minimize the window. This results in a nested O(n * m) pattern. |
| Worst Case | O(n * m) | In the worst case, for each character in S (size n), we have to scan through all of T (size m) to check for a subsequence match, and then walk backward to find the optimal window start. This results in O(n * m) time. |