awelgorithms

Slide by dropping left and adding right

Updated

After the first window [0,k), each step i from k to n-1 does: drop a[i-k], add a[i]. L and R both increase by 1. Length stays k.

What to focus on

One exclude and one include per i. Do not rescan the k cells. Stop when i would equal n. If n == k there is only the seed window.

Worked examples

two slides

a = [1, 2, 3, 4], k=2
  1. seed [1,2]
  2. i=2 drop a[0]=1 add a[2]=3 → [2,3]
  3. i=3 drop a[1]=2 add a[3]=4 → [3,4]

Result: windows [1,2], [2,3], [3,4]

one slide

a = [4, 1, 9], k=2
  1. seed [4,1]
  2. i=2 drop 4 add 9 → [1,9]

Result: windows [4,1], [1,9]

no slide

a = [4, 1], k=2
  1. seed [4,1]
  2. i would start at 2 = n, stop

Result: only [4, 1]

Try it

Write slideK(a, k). a is an array of integers. k is the fixed length. Each slide drops a[i-k] and adds a[i]. The window always includes k cells. Print each window. Return nothing. On [1, 2, 3, 4] k=2; [4, 1, 9] k=2; [4, 1] k=2.

a is nonempty. 1 ≤ k ≤ n.

LeetCode problems that use this skill