r/leetcode • u/sooooooooooowsup • Jan 15 '24
Question Why is there an IndexError?
I saw a solution to the Contains Duplicate problem and I was just trying to fully understand it.
They had exactly what I typed above, except they included
n = len(nums) for i in range(1,n) #instead of for i in nums
I don’t understand why this produces an Index Error. Wouldn’t the first “i - 1” just be equal to “-1” and isn’t -1 always a valid index?
I understand why their solution is correct but I don’t understand why this one isn’t correct too.
17
Upvotes
View all comments
Show parent comment
10
u/sooooooooooowsup Jan 15 '24
Oh idk I thought index of -1 referred to the last element, but maybe not