Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
In the Brute Force Python Solution why is "for i in range(len(arr)-K+1) " used i...

srilu

May 7, 2022

In the Brute Force Python Solution why is "for i in range(len(arr)-K+1) " used instead of just " for i in range(K)" ? Aren't these two conditions the same thing?

0

0

Comments
Comments
T
Ting 3 years ago

because the lenth of a subarray should be k. if we use "for i in range(k)", in the next lines, when i = len(nums) -1 and k > 1, the j in line "for j in range(i, i + k)" will be out of range.

M
Mike Xu3 years ago

They are not the same thing. (len(arr)-K+1) gives you the length of the result array, basically this is how many sub array of K continuous elements there are in the input array. Not the same as K.

A
Andrei 2 years ago

Just to ad to Mike;s answer:

arr.size() - K + 1 is required to determine how many subarrays there are within the input array, with the assumption that the size of the input array is larger than K. 🙂

arr.size() - K - this will calculate how many subarrays we can find ...

On this page