
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_substring(s: str, t: str) -> str:
from collections import Counter
need = Counter(t)
window = {}
left = right = 0
valid = 0
start = 0
min_len = float('inf')
while right < len(s):
c = s[right]
right += 1
if c in need:
window[c] = window.get(c, 0) + 1
if window[c] == need[c]:
valid += 1
while valid == len(need):
if right - left < min_len:
start = left
min_len = right - left
d = s[left]
left += 1
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return s[start:start + min_len] if min_len != float('inf') else ""
# Example usage
s = "ADOBECODEBANC"
t = "ABC"
print(min_window_substring(s, t)) # Output: BANC| Case | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(n) | In the best case, every character in 't' appears early in 's', allowing the window to be minimized quickly. However, we still scan each character in 's' once using the right pointer, and potentially once with the left pointer, resulting in O(n) total operations. |
| Average Case | O(n) | On average, each character in 's' is visited at most twice — once by the right pointer when expanding the window, and once by the left pointer when shrinking it. Thus, the total time complexity is linear with respect to the length of 's'. |
| Worst Case | O(n) | In the worst case, the algorithm expands the window to the end of 's' and then shrinks it step-by-step from the left. Still, each character is processed at most twice, resulting in O(n) time. |