Sliding Window

Templates

def slidingWindow(s: str):
    window = ...

    left, right = 0, 0
    while right < len(s):
        # c 是将移入窗口的字符
        c = s[right]
        window.add(c)
        # 增大窗口
        right += 1
        # 进行窗口内数据的一系列更新
        ...

        # print(f"window: [{left}, {right})")

        # 判断左侧窗口是否要收缩
        while left < right and window needs shrink:
            # d 是将移出窗口的字符
            d = s[left]
            window.remove(d)
            # 缩小窗口
            left += 1
            # 进行窗口内数据的一系列更新
            ...

Question types

Fixed size sliding window

Variable size sliding window

	l = 0
	cache = {}
	maxLen = 0
	
	for r in range(length):
		while s[r] is True:
			cache.remove(s[l])
			l += 1

		cache.add(s[r])
		maxLen = max(maxLen, r - l + 1)

	return maxLen

Double Ended Queue

239. Sliding Window Maximum

Remove duplicates with fast slow pointer

80. Remove Duplicates from Sorted Array II

Method Related Questions
Variable length sliding window:
- Increment r while condition True
- Decrement l while condition False
- Update max
3. Longest Substring Without Repeating Characters, 2461. Maximum Sum of Distinct Subarrays With Length K
Fixed length sliding window:
- Compute short length first
- Compare once first
- Iterate through the solutions then
567. Permutation in String
Max double ended queue
- Keep the maximum at the front of the queue
- Remove from the queue if it is smaller than newly append element
239. Sliding Window Maximum
File confidence date difficulty note
239. Sliding Window Maximum 🟡 April 01, 2024 - -
1838. Frequency of the Most Frequent Element 🔴 July 29, 2024 medium Variable size sliding window, compare the window total + k to window length * target value
1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit 🔴 October 31, 2024 medium Two deque, record the max and min at each position, pop out of it if outside of the limit
121. Best Time to Buy and Sell Stock 🟡 November 11, 2024 - -
File confidence date difficulty note
209. Minimum Size Subarray Sum 🟢 March 03, 2024 medium -
567. Permutation in String 🟢 March 17, 2024 - -
424. Longest Repeating Character Replacement 🟢 March 17, 2024 - -
53. Maximum Subarray 🟢 March 26, 2024 - -
1004. Max Consecutive Ones III 🟢 March 28, 2024 - -
2461. Maximum Sum of Distinct Subarrays With Length K 🟢 January 11, 2025 medium -