educative.io

Shrinking the sliding window unnecessary

For this problem, it seems that we don’t actually ever have to shrink the sliding window: we can simply grow it until we hit k elements, then slide it (deducting the element on the left from the dictionary and adding a new element on the right). Is this accurate, or is there some counter-example I’m not thinking of?

1 Like

I’d also like to know the answer to this. My initial solution also only removed one element from the left side at a time and it passed all test cases. My thinking was that in our outer loop we are only ever adding one character at a time, so if we ever go over the character count of k we should only need to remove one character from the left side to get back to our required character count for the substring.