KatInterview

Fixed-Width Window Totals and Rolling Median Over a Stream

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchsliding-windowtwo-heapsmedian

Last 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, k equal to the array length, k larger 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.