-2

Question is : Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k

Ex 1: Input: nums = [1,2,3,1], k = 3 Output: true

My solution is

def containsNearbyDuplicate(nums ,k):
    i = 0
    for j in range(1,len(nums)):
        if nums[i] == nums[j]:
            if abs(i-j) <= k:
                return True
            return False
        i += 1
nums = [1,2,3,1,2,3]
k = 2
containsNearbyDuplicate(nums ,k)

What's wrong here ? I am using Sliding-Window approach.

  • "Not working" is not an adequate description of what's wrong. What [debugging](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) have you tried to narrow down the cause of the problem? You need to perform basic diagnosis to include with your post. At the very least, print the suspected values at the point of error and trace them back to their sources Show where the intermediate results deviate from the ones you expect. Please take the [tour], and read [ask] and the [question checklist](//meta.stackoverflow.com/q/260648/843953) – Pranav Hosangadi Jul 14 '21 at 17:00

1 Answers1

0
def containsNearbyDuplicate(nums ,k):
    if len(nums)==len(set(nums)):
        return False
    for i in range(len(nums)):
        for j in range(i+1,len(nums)):
            if nums[i] == nums[j] and abs(i-j)<=k:
                return True
    return False
nums = [1,2,3,1,2,3]
k = 2
print(containsNearbyDuplicate(nums ,k)) # it will return False

you are using for loop so it will execute only once and after that it will terminate

Shantanu
  • 1
  • 1