Typorithm · medium

Sliding Window

sliding-windowpatternssubarrayrunning-sum
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Sliding Window

0%

Basic Patterns

A sliding window reuses the previous sum instead of re-adding k values.

Recomputing every window from scratch costs O(n·k). The window trick reuses overlap.

When the window slides one step, only one value enters and one value leaves.

Updating the running sum with that difference turns the whole scan into O(n).

01

Seed the sum with the first k values.

02

Slide: add entering, subtract leaving.

03

Track the best while sliding.

function maxWindowSum(arr, k) {
  let sum = 0;

  for (let i = 0; i < k; i++) {
    sum += arr[i];
  }

  let best = sum;

  for (let i = k; i < arr.length; i++) {
    sum += arr[i] - arr[i - k];
    best = Math.max(best, sum);
  }

  return best;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. First window

Sum the first k values once to seed the window.

for (let i = 0; i < k; i++)

2. Best so far

The first window is the best answer until a better one appears.

let best = sum

3. Slide the window

Add the entering value and subtract the leaving value in one step.

sum += arr[i] - arr[i - k]

4. Track maximum

Compare the new window sum with the best seen so far.

best = Math.max(best, sum)

5. Return answer

After one pass, best holds the maximum window sum.

return best

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Sliding Window: Lesson & Practice · Typorithm | ApplyDjinn