educative.io

Upper bound of for loop

  for i in range(len(arr)-2):

In the solution left is calculated by doing
left = i + 1

and right is right = len(array) -1

right will never go out of bounds and left can only go out of bounds by 1 so shouldn’t the upper bounds be len(arr)-1 ?

Hi @wvg,
Left will go out of bounds by 1 if the condition would be len(arr)-1. Let’s take an example

arr = [-1, 0, 2, 3]
The array’s index, as we know, begins at 0. The result of len(arr)-1 at the last iteration is 3. As a result, the left = 4 and this index number does not exist in our array because the array arr’s last index number is 3.
I hope this will help.