I'm posting a two-pointer, sliding-window problem of LeetCode (Minimum Window Substring) solved with Python. If you have time and would like to review the code, please do so, I appreciate that.
On LeetCode, we are only allowed to change the variable names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).
Problem
Given a string
base_string
and a stringtarget
, find the minimum window inbase_string
which will contain all the characters intarget
in complexity O(n).Example:
Input:
base_string
= "ADOBECODEBANC",target
= "ABC" Output: "BANC" Note:If there is no such window in
base_string
that covers all characters intarget
, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window inbase_string
.
Solution 1
import collections class Solution: def minWindow(self, base_string: str, target: str) -> str: count_map = collections.Counter(target) left = 0 min_left, min_right = 0, 0 target_length = len(target) for right, char in enumerate(base_string, 1): target_length -= count_map[char] > 0 count_map[char] -= 1 if not target_length: while left < right and count_map[base_string[left]] < 0: count_map[base_string[left]], left = -~count_map[base_string[left]], -~left if not min_right or right - left <= min_right - min_left: min_left, min_right = left, right return base_string[min_left:min_right]
Solution 2
import collections class Solution: def minWindow(self, base_string: str, target: str) -> str: count_map = collections.Counter(target) left, right = 0, 0 min_left, min_right, min_window = 0, float('inf'), '' target_length = len(target) while right < len(base_string): if count_map[base_string[right]] > 0: target_length -= 1 count_map[base_string[right]] -= 1 while target_length == 0: sliding_window = -~right - left if not min_window or sliding_window < len(min_window): min_window = base_string[left:-~right] count_map[base_string[left]] += 1 if count_map[base_string[left]] > 0: target_length += 1 left += 1 right += 1 return min_window