Python. best possible solution I think.

  • 0

    We don't need an array in the hashtable to hold every position of every element we encounter, since we can just hold the LAST
    position of every distinct integer we encounter.
    So as we iterate over the numbers, if we have already seen the current integer, we just care about the last one we saw. If it meets
    the requirments, we return True. If not, we just add it as the last index in the hashtable.

    class Solution(object):
        def containsNearbyDuplicate(self, nums, k):
            h = {}
            for i, num in enumerate(nums):
                if num in h and i - h[num] <= k:
                    return True
                h[num] = i
            return False

  • 0

    I used the same logic it says TLE. Did your code passed all test cases???

Log in to reply

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