Check Duplicates with Criteria

By   Tewodros   Date Posted: Nov. 2, 2023  Hits: 352   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given an  a list of  array nums and a target number k, return true if there are two i and j in the array indices such that nums[i] == nums[j] and abs(i - j) <= k.

Example

nums = 1,4,3,1,9 

k = 2

Answer: False

Example 

nums = 10,4,3,1,9,1

k = 2

Answer: True

Solution:

Dictionaries can be used to solve this problem.

we need to check the dictionary if you already saved it, and if you already save this number, will calculate the distance between this number and the previously saved number, and if that gap is less than or equal to the target value we return true. otherwise, will replace the key with this new number and we keep searching for the new gap.

public bool ContainsNearbyDuplicate(int[] nums, int k) {

         Dictionary<int, int> dict = new();


        for (int i = 0; i < nums.Length; i++)

        {

            if (!dict.ContainsKey(nums[i]))

                dict.Add(nums[i], i);

            else

            {

                int start = dict[nums[i]];

                int end = i;

                int diff = Math.Abs(start - end);

                if (diff <= k)

                   return true;

               else

                {

                    dict.Remove(nums[i]);

                    dict.Add(nums[i], i);

                } 

            }

        }

      return false;

            

    }

}

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* gxlcks

Back to Top