Description

The window changes size to fit the target condition; you grow it until the condition fails, then shrink it till the condition is met again.
?

Reach for when

Runtime

O(n)

Visualization

Variable Sliding Window-1783988873691.webp

Pseudocode

l = 0
r = 0
while r < len(array)
	while over extended past the condition:
		decrease state by l
		l+=1
	r+=1
	update the state by r
return answer

Code

def longest_window(arr):
	state = new_state()
	l = 0
	best = 0
	for r in range(len(arr)):
		add(state, arr[r])
		while not valid(state):
			remove(state, arr[l])
			l += 1
		best = max(best, r - l + 1) 
	return best

def shortest_window(arr):
	state = new_state()
	l = 0
	best = float("inf")
	for r in range(len(arr)):
		add(state, arr[r])
		while valid(state):
			best = min(best, r - l + 1)
			remove(state, arr[l])
			l += 1
	return best if best != float("inf") else 0