5 Sliding Window Variations You Will See in Interviews

Sliding window problems all look the same from far away: find the best contiguous piece of an array or string. What changes is the constraint the window has to respect.

1) Fixed Window Length

Fixed window length

You get an array and a length k, and look for the best subarray of exactly k elements.

"Given an array visitors of daily website visits, return the highest total over any 3 consecutive days."

k = 3

Best 3-day total = 26

2) Sum Limit

Sum limit

You get a limit k and want the longest subarray whose sum stays within it:

- below k - exactly k - at most k

"Given an array minutes and a budget k, return the most consecutive tasks you can finish within k minutes."

k = 9

Longest length = 4

3) Count Limit

Count limit

You want the longest stretch that contains at most k of something, such as zeros, vowels or one specific character.

"Return the longest run of 1s you can get by flipping at most one 0."

k = 1

Longest length = 6

4) No Repeats

No repeats

You want the longest stretch in which every element is different.

"Given a string s, return the length of its longest substring with no repeated letters."

s = "abcabd"

Longest length = 4

5) Counting Windows

Counting windows

Instead of the best window, you count how many windows satisfy the constraint.

"Given positive integers nums and k, count the subarrays whose product is less than k."

k = 50

When the window ends at index r, it adds r - l + 1 new subarrays.

Total = 1 + 2 + 2 + 3 = 8