Monday, June 5, 2017

Contains Duplicate II


Problem Statement


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 at most k.

Basically we need to validate if we have near by duplicate

Link to Github :code


Example



Input: k = 3, arr[] = {1, 2, 3, 4, 1, 2, 3, 4}
Output: false
All duplicates are more than k distance away.

Input: k = 3, arr[] = {1, 2, 3, 1, 4, 5}
Output: true
1 is repeated at distance 3.

Input: k = 3, arr[] = {1, 2, 3, 4, 5}
Output: false

Input: k = 3, arr[] = {1, 2, 3, 4, 4}
Output: true


Solution

  • We need to use HashSet to store elements of the array
  • We need to iterate through the array with i value less than K
  • If i value is less than k then add the value to HashSet
  • When there is duplicate then insert fails. We need to return true else false
  • If i is greater then k,then we need to delete the first element in the HashSet
if(i>k){ set.remove(arr[i]-k-1); }



public static boolean get (int [] num , int k) 
 {
  //Use hash set to check for duplicates
  Set<Integer> set = new HashSet<Integer>();
  
  for(int i=0;i<num.length;i++)
  {
   if(i>k)
   {
    set.remove(num[i-k-1]);
   }
   //Here we are adding i values to the hashSet.
   //If there is a duplicate then add would fail
   if(!set.add(num[i]))
    return true;
  }
  return false;
 }

No comments:

Post a Comment