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.
-
HINT: If a subarray of length $k$ starts at position $m$, at what position does it end? – Brian M. Scott Aug 16 '20 at 23:39
1 Answers
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.
- 3,474
- 1
- 12
- 23
-
1I've edited the question. I'm sorry I meant contiguous subarrays, does the proof still hold? – coolusername Aug 16 '20 at 23:57
-
Got it, thanks a lot! Is there any way to write a proof for this though? – coolusername Aug 21 '20 at 20:46
-
No, I don't see how we could prove this using induction, please let me know if you do. – coolusername Aug 21 '20 at 21:00