Sliding Window
- Pronunciation
- SLY-ding WIN-doh
In short
The sliding window technique solves problems on contiguous parts of an array or string by updating a window as it slides instead of recomputing each subarray.
What is the sliding window technique?
Take the problem of finding the largest sum of any k consecutive numbers. Summing each group separately costs O(n·k). A sliding window keeps the sum of the current k numbers; to move one step, it adds the number entering on the right and subtracts the one leaving on the left. Every element is added and removed once, so the whole scan is O(n).
Windows can be fixed or variable in size. A variable window grows by moving its right edge and shrinks by moving its left edge whenever a condition breaks. The classic example is the longest substring without repeating characters: extend the window while letters are unique, and when a repeat appears, move the left edge past the earlier copy, tracking the letters inside with a set or a map.
The same idea appears outside coding interviews: moving averages in analytics, rate limiters that count requests in the last minute, network protocols such as TCP that track a window of unacknowledged data, and streaming systems that aggregate events over time windows.
A common misconception is that sliding window works for any subarray question. It needs contiguous elements and a condition that changes predictably as the window grows or shrinks. Problems about subsequences that can skip elements, or windows over negative numbers where shrinking doesn't reliably help, usually need other techniques such as prefix sums or dynamic programming.
Key takeaways
- A sliding window tracks a contiguous range and updates it step by step.
- Each element enters and leaves once, so scans are O(n).
- Fixed windows keep size k; variable windows grow and shrink by a condition.
- Rate limiters, moving averages and TCP use the same idea.
- It needs contiguous elements and a predictable condition.
Example
def max_sum_of_k(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # one in on the right, one out on the left
best = max(best, window)
return best
def longest_unique_substring(s):
seen, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1 # shrink past the earlier copy
seen[ch] = right
best = max(best, right - left + 1)
return best
print(max_sum_of_k([2, 1, 5, 1, 3, 2], 3)) # 9
print(longest_unique_substring("abcabcbb")) # 3 ("abc")Readers ask
What kinds of problems use a sliding window?
Problems about contiguous subarrays or substrings: maximum or minimum sums over k elements, the longest or shortest range meeting a condition, counting distinct items in ranges, and finding anagrams within a string.
What is the time complexity of a sliding window?
Usually O(n), because each element enters the window once and leaves it at most once, even though the window's size changes along the way.
How is a sliding window used in rate limiting?
A sliding window rate limiter counts requests in the most recent time span, such as the last 60 seconds, rather than in fixed calendar minutes, which avoids bursts at the boundary between two minutes.
See also
- Two PointersData Structures, p. 35The two pointers technique walks an array or list with two indexes moved by simple rules, turning many problems that seem to need nested loops into one pass.
- ArrayProgramming Fundamentals, p. 3An array is an ordered collection of values stored under one name, where each item is accessed by its numeric position, called an index, usually starting at 0.
- StringProgramming Fundamentals, p. 54A string is a data type that represents text as an ordered sequence of characters, such as a name, a sentence, a URL, or the contents of a file.
- Rate LimitingBackend & APIs, p. 37Rate limiting is a technique that caps how many requests a client can make to a server or API within a time window, protecting it from abuse and overload.
- Dynamic ProgrammingData Structures, p. 14Dynamic programming is a technique for solving problems by breaking them into overlapping subproblems and storing each answer so none is solved twice.
- Big O NotationProgramming Fundamentals, p. 6Big O notation describes how an algorithm's running time or memory use grows as its input gets larger, focusing on the growth rate rather than exact speed.
Spotted a mistake or something missing on this page?Suggest an edit