Monday, October 19, 2020

Contains nearby duplicate

Problem: Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is not more than k.

Example:

Input: nums = [19, 20, 22, 19, 17], k = 3
Output: true


Approach: Its not a complex problem to solve. We just need to maintain a hash which will have value as key and index as value. We will keep adding this pair to hash; hash[nums[i]] = i. In case of collision we just need to check if i - hash[nums[i]] <= k, if yes return true.


Implementation in C#:

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

        {

            if (nums?.Length <= 1)

            {

                return false;

            }

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

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

            {

                if (hash.ContainsKey(nums[i]))

                {

                    if (i - hash[nums[i]] <= k)

                    {

                        return true;

                    }

                    hash[nums[i]] = i;        

                }

                else

                {

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

                }

            }

            return false;

        }


Complexity: O(n)

No comments:

Post a Comment