Skip to the solution
MediumDSA10 min read

What is the sliding window technique?

213 views

The problem

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, never sum(arr[i:i+k]) per step (each slice copies k items); collections.Counter or defaultdict(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.

  • sliding-window

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read · 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonFixed window: largest sum of k consecutive values, and the work it saves
PythonVariable windows: shortest subarray with sum at least target, longest ones with k flips

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 114 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is amortized analysis?

Continue