Sliding Window: Beginner
What you will be able to do
Spotting the Pattern
Recognize sliding window problems instantly
- ▸"contiguous subarray" or "consecutive elements" (NOT subsequence)
- ▸"window of size K" or "K consecutive"
- ▸"rolling average" or "rolling sum"
- ▸"longest substring" or "shortest subarray"
- ▸"at most K distinct" or "sum less than target"
- ▸Any problem where brute force involves nested loops over subarrays
The Incremental Thinking Test
- Sum each window from scratch
- Inner loop of K additions per window
- Recomputes shared elements
- Same as full-refresh ETL
- Compute first window, then slide
- One addition + one subtraction per slide
- Reuses computation from previous window
- Same as incremental ETL
Fixed-Width Windows: The Add-Subtract Trick
Implement fixed-width windows with add-subtract
Maximum Sum of K Consecutive Elements
Maximum Average Subarray (LeetCode 643)
Edge Cases to Name Before Coding
| Edge Case | What Happens | How to Handle |
|---|---|---|
| K > len(arr) | Cannot form a window | Return 0 or raise ValueError immediately |
| K = len(arr) | Only one window: the entire array | Return sum of entire array |
| All negative numbers | Maximum sum is the least negative window | Algorithm works unchanged |
| K = 1 | Each element is its own window | Returns max(arr), which is correct |
Name these edge cases BEFORE writing code. Say: 'First, let me handle edge cases. If K is larger than the array, there is no valid window. If K equals the array length, there is exactly one window.' The interviewer has a rubric item for proactive edge case handling. Naming them first is a 4/4 signal.
Window State: Beyond Sums
Maintain window state correctly
Window with a Set: Contains Duplicate II (LeetCode 219)
Window with a Counter: Maximum of All Subarrays
Window with a Product
- Delete counter keys when they reach zero count
- Use a set for 'contains' checks, a counter for frequency
- Handle the 'window not yet full' phase (i < k) explicitly
- State the window state type before coding: 'I will maintain a set/counter/sum'
- Leave zero-count keys in your counter (corrupts distinct counts)
- Use 'if' instead of 'while' for variable-width contraction
- Forget to remove the leaving element when the window slides
- Reset the left pointer to 0 (destroys O(n) guarantee)
The Expand-Contract Framework
Apply the expand-contract framework
The Universal Template
Fixed-Width vs Variable-Width
- Window always has exactly K elements
- Contract is simple: if window > K, remove left
- No while loop needed for contraction
- Examples: max sum of K elements, rolling average
- Window grows and shrinks based on constraint
- Contract uses while loop: shrink until valid
- State is more complex (set, counter, map)
- Examples: longest substring, shortest subarray
The three-question framework (state, constraint, objective) is the fastest way to decompose any sliding window problem. Say it out loud: 'The state is a frequency counter. The constraint is at most K distinct characters. The objective is the maximum window length.' Three sentences, and the structure of your solution is clear.
Sliding Windows in Data Pipelines
Connect sliding windows to real pipeline patterns
Rolling Aggregations
Rate Limiting
Session Windowing
- ▸Rolling aggregations: 7-day revenue, 30-day retention, 1-hour error rate
- ▸Rate limiting: allow at most N requests per T seconds
- ▸Session windowing: group events into sessions based on inactivity gaps
- ▸Anomaly detection: flag values outside 3 standard deviations of the rolling mean
> You are in a phone screen. The interviewer asks: 'Given an array of integers and an integer K, find the contiguous subarray of length K with the maximum average.'
Stop recomputing everything. Slide the window, update the delta.
- Category
- Python
- Difficulty
- beginner
- Duration
- 25 minutes
- Challenges
- 0 hands-on challenges
Topics covered: Spotting the Pattern, Fixed-Width Windows: The Add-Subtract Trick, Window State: Beyond Sums, The Expand-Contract Framework, Sliding Windows in Data Pipelines
Lesson Sections
- Spotting the Pattern (concepts: pySlidingWindow, pyPatternRecognition)
The distinction between sliding window and other patterns comes down to one word: contiguous. If the problem asks about a contiguous subarray or substring, sliding window is on the table. If it asks about a subsequence (elements do not need to be adjacent), sliding window is the wrong tool. This is the most common misidentification. Candidates try to slide a window on a subsequence problem and waste 15 minutes before realizing the approach does not work. Read the problem statement carefully. 'Su
- Fixed-Width Windows: The Add-Subtract Trick (concepts: pyFixedWindow, pyWindowSum)
Fixed-width sliding windows are the simplest form. The window is always exactly K elements wide. As the window slides one position right, one element enters on the right and one element leaves on the left. The window state (sum, count, product) is updated by adding the entering element and subtracting the leaving element. No inner loop needed. One pass through the array. Maximum Sum of K Consecutive Elements This is the canonical beginner sliding window problem and the most frequently asked warm
- Window State: Beyond Sums (concepts: pyWindowState, pyWindowSet, pyWindowCounter)
Sums are the simplest window state. But many sliding window problems require richer state: a set of elements in the window, a frequency counter, a running product, or a boolean condition. The principle is the same: update the state incrementally as elements enter and leave. But the update logic gets more interesting. Window with a Set: Contains Duplicate II (LeetCode 219) Given an array, determine if there are two distinct indices i and j such that arr[i] == arr[j] and |i - j| <= K. Translation:
- The Expand-Contract Framework (concepts: pyExpandContract, pyWindowTemplate)
Every sliding window problem, fixed or variable width, follows the same three-step loop: expand, contract, record. The right pointer expands the window by adding an element. The left pointer contracts the window by removing elements until the constraint is satisfied. Then you record the current window as a potential answer. This expand-contract-record rhythm is the template. Memorize it. Every sliding window problem is a variation of this template. The Universal Template For fixed-width windows,
- Sliding Windows in Data Pipelines (concepts: pyRollingAgg, pyRateLimiter, pySessionWindow)
Here is where you turn a coding answer into a data engineering answer. Sliding windows are not just LeetCode problems. They are the foundation of rolling aggregations, session analysis, anomaly detection, and rate limiting in production data systems. Every time you write AVG(revenue) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) in SQL, you are using a fixed-width sliding window. When you use Flink's SlidingEventTimeWindows, you are using the same algorithm. Connecting the interv