I am working through a challenge and I'm trying to use a nested for loop to solve it. The challenge asks in a given array of integers nums
and an integer k
, determine whether there are two distinct indices i
and j
in the array where nums[i] = nums[j]
and the absolute difference between i
and j
is less than or equal to k
.
This is my attempt:
def containsCloseNums(nums, k):
for i in nums:
for j in nums:
if (nums[i] == nums[j]) and abs(i-k) <= k:
return True
else:
return False
But this is the error I'm getting:
Traceback (most recent call last):
main.py3 in the pre-written template, in getUserOutputs
userOutput = _rundyxlc(testInputs[i])
main.py3 in the pre-written template, in _rundyxlc
return containsCloseNums(*_fArgs_zeutcbsrcmec)
main.py3 in the pre-written template, in containsCloseNums
if (nums[i] == nums[j]) and abs(i-j) <= k:
IndexError: list index out of range
I don't see a reason for why I'd be out of index because I'm not incrementing beyond the list's length.
I appreciate all help but since this is a challenge, it is more beneficial for me to know why my logic didn't work as opposed to just spitting out an answer.