Sliding window is not only the index offset
本文最后更新于 2025年11月11日 下午
The sliding window MUST operate within a single loop! Every time adjusting only one index per iteration! Never move both simultaneously otherwise it will be O(n^2)!
Background
Very funny, I just unexpectlly find out that it is 3rd of Leetcode, but I only remembered that it should be resolved by sliding window.
Topic
A sliding window is not merely defined by two numerical index: the left offset and the right offset.
Intuitive version
We init left and right index, and between string[left: right] slide is the windows, this is very intuitive.
1 | |
The coding process is so smoothly, it must be that I was too NERVOUS to coding a O(n^3) algorithm.
What A STUPID man!
The window slide only in a loop, move right and left should be in a same leveled loop!
That time I got a outter loop to move right, and another inner loop to move left, and what is more, maintain a s[now_left: now_right+1] to check whether it contains duplicate char each loop.
With above code, it seems that it should a Medium…
And with replacing record_set -> record_dict, it IS O(n) now.
It’s over. All is lost.
Slide with record
In above code, you can see that the set()/dict() is always add a element and move the same one, and what is more, there are so many break when right < len and now char not in record_dict, so we could use a dict to record index, and reassign it to means “Oh, now window contains repeated char, we should slide it to get a new window”.
But the time complex is same as intuitive version, just substract some branch, if nervious, just use initial version!
1 | |