awelgorithms

Fix the window length in advance

Updated

k is given. Every window has length k. You do not discover length. You slide a block of k cells.

What to focus on

Length is always k = R-L+1. For n cells there are n-k+1 windows.

Worked examples

k=2 on four

a = [1, 2, 3, 4], k=2
  1. windows [0,1], [1,2], [2,3]
  2. each has length 2
  3. count = 4-2+1 = 3

Result: 3 windows

k=2 on three

a = [4, 1, 9], k=2
  1. [0,1] then [1,2]
  2. count = 2

Result: 2 windows

k bigger than n

a = [7], k=2
  1. n=1 < 2
  2. no block of 2 cells

Result: 0 windows

Try it

Write windowCount(n, k). n is the array length. k is the fixed window length. Each window includes k cells, R-L+1 = k. Count is max(0, n-k+1). Return the count. On [1, 2, 3, 4] k=2 → 3. On [4, 1, 9] k=2 → 2. On [7] k=2 → 0.

a is nonempty. k ≥ 1. When k > n the window count is 0.

LeetCode problems that use this skill