3

For example: Given the array $[1,2,3,4,5,6,7,8,9]$ where $N$ is the length of the array and $k$ is the subarray size. Here $N = 9$ and given $k = 5$, we find that $N-k+1$ contiguous subarrays of size $k$ can be found. How can we prove $N-k+1$ as the number of contiguous subarrays of size $k$? I'm sure it is intuitive, but I can't wrap my head around it.

coolusername
  • 33
  • 1
  • 4

1 Answers1

5

Instead of looking at the answer for a general value of $k$, let's look at specific examples.

First of all, how many subarrays of length one are there? The answer to this question is $n$. Why? Because we can choose any of the $n$ elements to be in our array.

Next, how many subarrays of length two are there? The answer to this question is $n - 1$. Why? Because we can choose any of the $n$ elements except for the last element to be the "start" of the array (and the element directly after it will also be included). Note that we cannot "start" the array at the last element since there's no element to include afterward.

Continuing with the exact same reasoning, we can see that the answer for subarrays of length $k$ must be $n - (k - 1) = n - k + 1$ since we're able to "start" the array anywhere except for the last $k - 1$ positions.

Ekesh Kumar
  • 3,474
  • 1
  • 12
  • 23