Fixed-Width Window Totals and Rolling Median Over a Stream
Heaps, Sorting & SearchModel answerLast updated
Find the best sum over any run of k adjacent numbers, then track the median of the latest k values in a live stream, discussing data structures, parallelism and trade-offs.
This problem has two connected parts. Both concern a window of fixed size k moving across a sequence of integers.
Part 1: Best window total
You are given an integer array nums and a window size k. Find the largest sum achievable by any block of k consecutive elements.
- Describe an algorithm and state its time and space complexity.
- Explain what can be optimized, and how you would handle very large inputs by running the work concurrently.
- State how you handle inputs where no valid window exists, and arrays containing only negative numbers.
Part 2: Rolling median of a live stream
Integers arrive one at a time. After each arrival, report the median of the most recent k values. Until k values have been seen, report that no median is available yet.
- For an even
k, the median is the average of the two middle values. - Choose the data structures (for example two heaps, a hash map, or something else) and justify them.
- Explain how a value is removed when it falls out of the window.
- Discuss the trade-offs between alternatives, and how the design behaves with many streams or concurrent readers.
What to cover
- A clear approach for each part, with time and space complexity.
- Edge cases:
k = 1,kequal to the array length,klarger than the array, duplicates, negative numbers. - Working code for the main algorithm in each part, or a precise description of it.
Hints
Hint 1
Neighboring windows overlap in all but one element. How can you derive one window's sum from the previous one without re-adding everything?
Hint 2
For the concurrent version, split the range of window start positions among workers. Think about what extra elements each worker must read so no window that crosses a boundary is lost, and how to combine the partial results.
Hint 3
A running sum cannot give a median, so you need order. Keep the lower half in a max-heap and the upper half in a min-heap, with sizes differing by at most one.
Hint 4
Heaps cannot remove an arbitrary element cheaply. Consider marking outgoing values as pending deletion in a hash map, tracking logical sizes, and discarding stale entries only when they reach a heap top.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Best window total
Approach
Recomputing every window from scratch costs O(n·k). Consecutive windows share k-1 elements, so slide by one position: add the element entering and subtract the one leaving.
sum(i) = sum(i-1) + nums[i] - nums[i-k]
Compute the first window directly, then update the sum for each later position while tracking the maximum. There are n-k+1 windows and each is visited once. The update is an exact identity, and no window is skipped, so negative values cause no problems.
Complexity
- Time: O(n), one pass with O(1) work per step.
- Space: O(1).
- Prefix sums also give O(1) per window but need O(n) memory. They are worthwhile only if you must answer queries for many different
k. - In fixed-width languages, use a 64-bit accumulator to avoid overflow.
- The scan is sequential, so it is cache-friendly.
Edge cases
- If
k < 1ork > n, there is no valid window. Raise an error (agree on this contract up front). - If
k == n, there is exactly one window. - For all-negative input, initialize the best value from the first window, not from
0.
Concurrent version
The serial algorithm is already linear, so parallelism pays off only for huge or sharded data.
- Split the window start indices
[0, n-k]into P contiguous ranges. - A worker responsible for starts
[s, e]readsnums[s : e+k]. Neighboring slices therefore overlap byk-1elements, which ensures boundary-crossing windows are not missed. - Each worker runs the serial algorithm and returns its local maximum.
- Reduce with
max, which is associative and commutative, so result order is irrelevant.
Cost is about O(n/P + k) per worker plus O(P) to combine. Alternatives: a parallel prefix scan followed by a parallel max(prefix[i+k] - prefix[i]); vectorized NumPy (cumsum differences); processes rather than threads in Python because of the GIL; or map/reduce over overlapped shards in a distributed setting.
from concurrent.futures import ProcessPoolExecutor
def max_window_sum(nums, k):
if k < 1 or k > len(nums):
raise ValueError("k must satisfy 1 <= k <= len(nums)")
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best
def parallel_max_window_sum(nums, k, workers=4):
if k < 1 or k > len(nums):
raise ValueError("k must satisfy 1 <= k <= len(nums)")
num_windows = len(nums) - k + 1
step = max(1, -(-num_windows // workers))
chunks = []
for start in range(0, num_windows, step):
last = min(start + step, num_windows) - 1
chunks.append(nums[start:last + k]) # k-1 overlap
with ProcessPoolExecutor(max_workers=workers) as pool:
return max(pool.map(max_window_sum, chunks, [k] * len(chunks)))
Part 2: Rolling median
Design
A median depends on order, so a running sum is not enough. Use two heaps:
low: a max-heap (negated values in Python) for the smaller half.high: a min-heap for the larger half.
Invariants: every element of low is at most every element of high, and size(low) equals size(high) or exceeds it by one. The median is low.top for odd k, or the mean of both tops for even k.
A deque stores arrival order so we know which value expires. The hard part is removing that value, since heaps do not support cheap arbitrary deletion. Use lazy deletion:
- Increment
delayed[value]in a hash map. - Decide which heap the value belongs to by comparing it with
low.top(at most that top meanslow). Decrement that heap's logical size. - Physically pop stale entries only when they reach the top of a heap (prune after every operation).
- Rebalance using logical sizes, moving a top element across if the size invariant breaks.
Equal values are interchangeable, so duplicates at the boundary do not break the counts.
Complexity
- Time: O(log k) amortized per element. Each value is pushed once and popped at most once.
- Space: O(k) for the deque and hash map, plus temporarily stale heap entries, which a periodic rebuild can cap.
Alternatives and trade-offs
| Approach | Update | Median | Notes |
|---|---|---|---|
Sorted list + bisect | O(k) shift | O(1) | Simplest, quick for small k |
| Two heaps + lazy deletion | O(log k) amortized | O(1) | Standard answer |
Balanced BST / SortedList | O(log k) | O(log k) | True deletion, supports any percentile |
| Order-statistic tree / skip list | O(log k) | O(log k) | Production choice for arbitrary quantiles |
| Fenwick tree over values | O(log V) | O(log V) | Best when value range V is small and bounded |
Concurrency and scale
- A single window is inherently sequential, so give each stream one writer and shard streams by key across workers or partitions.
- For concurrent readers, publish the latest median atomically rather than locking the heaps on every read.
- If approximate answers suffice at very large scale, quantile sketches (t-digest, KLL) trade exactness for mergeability.
Edge cases
- Window not yet full: return
None. k = 1: the median is the element itself.- Even
k: return a float average. - Duplicates and negatives work without special handling.
Common mistakes
- Forgetting the
k-1overlap when splitting work, which drops boundary windows. - Initializing the best sum to
0, which is wrong for all-negative arrays. - Using physical heap sizes instead of logical sizes, so stale entries corrupt the balance.
- Not pruning the tops after each update, which makes the median read a deleted value.
- Using integer division for even-
kmedians.