An Efficient Python 3 Solution to the Minimum Window Substring Problem
An efficient solution to this problem that beats 99.92% solutions in runtime and 98.79% in memory usage.
start = min_start = 0 |
Intuition
- Maintain a sliding window.
- Keep track of whether the window contains all characters in
t. - Also keep track of the “surplus” characters in the window.
- If it does, shrink the window by trimming the redundant characters from the start, by referring to the surplus characters table.
- Also keep track of the minimum window size and the corresponding window.
A Quick Prototype and Its Optimization
counter_t = Counter(t) |
There is a lot of room for optimization in the above code.
- The
Counterclass is handy but slow for this use case. - We can keep track of the
startandendindices of the window instead of the substring of the window itself. Alternatively, we can keep track of thestartindex and the length of the window. - We don’t have to trim the window at each interation, it is only needed when a valid window is found.
- As a side effect, when we trim window only when the window is valid, we no longer need to guard
startindex again out of range error.
Explanation of the Final Code
Here’s the final code with comments:
# Initialize the variables needed |
The use of counter variable significantly speeds up the algorithm. Otherwise, we would have to consult the table each time, and test whether max(table) == 0 to see if we found a valid window.
Some Optimization Tricks for Leetcode
s[min_start:][:min_w]is somehow much faster thans[min_start:min_start + min_w + 1]table[ord(c)]is faster thantable[ord(c) - ord('A')]- Initialize
min_wto a integer is slightly faster thanfloat('inf').