Contains Duplicates II

Problem

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Thought Process

  • Using a dictionary, linearly go through the array and check if the number already exists in the dictionary. If it does, the the abosulte difference between their indexes HOWEVER if the difference is more than k update the index of that number in the dictionary.

Solution

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        d = {}
        
        for i in range(len(nums)):
            if nums[i] in d:
                if abs(i - d[nums[i]]) <= k:
                    return True
            d[nums[i]] = i
        return False
                

Time Complexity

  • Time: O(n)

  • Space: O(n)

Last updated