Question presented to candidate: "What is the sliding window technique? Show me, in Python, the largest sum of any k consecutive numbers, and then a version where the window size is not fixed."
What a strong answer should cover:
- A window is a contiguous range
[left, right]; you update a running summary as it moves instead of recomputing it. - Fixed window (subtract the leaving element, add the entering one) versus variable window (expand right, shrink left by a rule).
- O(n) time because each pointer moves forward at most n times (amortized), versus O(n·k) or O(n²) recomputing.
- When it fails: the rule must be monotonic, so sums with negative numbers need prefix sums instead.
- Python specifics: compute
sum(arr[:k])once, neversum(arr[i:i+k])per step (each slice copies k items);collections.Counterordefaultdict(int)for character windows;float('inf')as a "no answer yet" sentinel; ints cannot overflow.
Clarifying questions expected:
- "Can the numbers be negative or zero?" — decides whether shrinking is valid.
- "What should I return if no window qualifies, or if k is larger than the array?"
Code / implementation expected: Yes — max_window_sum(arr, k) for the fixed window and one variable-window function such as min_subarray_len(target, nums), in Python.