Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Duplicate entries in Array

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.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

Could anyone tell me why the test case below is true?

[1,0,1,1]
1

The largest difference should be 2 which is greater than k = 1. Isn’t it?

>Solution :

You are right, 2 is larger than 1. However we still have other equal numbers which the difference of their abs value is <= 1. This means you should update the initial index of the value you mapped, initially 1 is mapped with 0 right, but later on it should be updated and mapped to 2. This would mean that abs values (2 – 3) <= 1…

for(int i = 0; i<nums.length; i++)
{
    if(map.containsKey(nums[i]) == true)
    {
        if(Math.abs(map.get(nums[i]) - i) <= k)
        {
            duplicate = true;
        }
        map.put(nums[i], i); // the update i was talking about
    }
    else
    {
        map.put(nums[i], i);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading