LC 219. Contains Duplicate II

Nilanjan Deb · April 1, 2020

Here I use unordered map to store position data to its corresponding value. Then traversing over the array and check for every numbers as it appear before or not and if it’s appear if the distance between them is less then the desired value. Remember about Corner cases.

This is my CPP solution.

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(nums.size()==0 || nums.size()==1 || k==0){
            return false;
        }
        unordered_map<int,int>umap;
        for(int i=0;i<nums.size();i++){
            if(umap.find(nums[i])!=umap.end() && i - umap[nums[i]]<=k)
                return true;
            umap[nums[i]] = i;
        }
        return false;
    }
};

Time Complexity O(n);



Dicussion Forum