LeetCode #219 Contains Duplicate II Solution & Explanation

LeetCode Problem

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.


Solution

This problem can be seen as part of a series related to the “Contains Duplicate” problem, with a slight difference. In this case, we need to consider the positions (indices) of elements.

See Here ➡ LeetCode #217 Contains Duplicate Solution & Explanation

C# Solution

Solution1

public class Solution {
    public bool ContainsNearbyDuplicate(int[] nums, int k) {
        Dictionary<int,int> dict =   new Dictionary<int,int>();

        for(int i = 0; i<nums.Length; i++)
        {
            if (!dict.ContainsKey(nums[i]))
            {
                dict.Add(nums[i], i);
            }
            else
            {
                if(i-dict[nums[i]]<=k)
                {
                    return true;
                }
                dict[nums[i]] = i;
            }
        }
        return false;
    }
}

We use a dictionary to store the integer and it’s last index to check.

Java Solution

Solution1

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,Integer>map =   new HashMap<Integer,Integer>();

        for(int i = 0; i<nums.length; i++)
        {
            if (map.containsKey(nums[i]))
            {
                if(i-map.get(nums[i])<=k)
                {
                    return true;
                }   
            }
            map.put(nums[i],i);
        }
        return false;
    }
}

Python3 Solution

Solution1

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        dict = {}

        for i in range (len(nums)):
            if (nums[i] in dict):
                if(i-dict[nums[i]]<=k):
                    return True

            dict[nums[i]] = i
        return False

JavaScript Solution

Solution1

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */
var containsNearbyDuplicate = function(nums, k) {
        const map =   new Map();

        for(let i = 0; i<nums.length; i++)
        {
            if (map.has(nums[i]))
            {
                if(i-map.get(nums[i])<=k)
                {
                    return true;
                }   
            }
            map.set(nums[i],i);
        }
        return false;
};

Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts or clicking ads, thanks you~~

If you got any problem about the explanation or you need other programming language solution, please feel free to let me know (either leave a comment or contact me by Messenger is ok!)

The problem link : Contains Duplicate II – LeetCode

Similar Question : LeetCode #217 Contains Duplicate Solution & Explanation

Some Random post

Leave a Reply

Your email address will not be published. Required fields are marked *