Time O(n), Space O(k) Python 3 Solution Using set(). [82ms]


  • 0
    # O(n), O(k)
    class Solution:
        def containsNearbyDuplicate(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: bool
            """
            if len(nums) == 0: return False
            
            window = set()
            for i in range(len(nums)):
                if i >= k+1: window.remove(nums[i-k-1])
                if nums[i] in window: 
                    return True
                else: 
                    window.add(nums[i])
            return False
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.