educative.io

For i in range len(nums) -2?

Is the len -2 necessary vs for i in range (len(nums))?
That passes all the test cases too

Hey @Max_Moffett,

I apologise for the late reply. I understand that you may have a different perspective on the problem, which made us look at it again. Since the while loop ensures that low can never be greater than high, our test cases pass even if we let the for loop iterate to the last value of i.

So why keep it? It is a minor performance optimization, eliminating up to two needless iterations. Also, it follows the design closely since at the start, high is fixed as the last element in the array and the while condition ensures that the highest value low can take on is high-1. Thus, to check the last three elements in the array, i need never be greater than high-2.

As always, we appreciate our valued users reaching out to us. Therefore, please write to us if you have any further queries, concerns, or suggestions in general.

We hope you enjoy your experience with us at Educative! Happy learning!

1 Like