Check if a given array contains duplicate elements within k distance from each other | Javascript program to Check if a given array contains duplicate elements within k distance from each other ; Creates an empty hashset ; Traverse the input array ; If already present n hash , then we found a duplicate within k distance ; Add this item to hashset ; Remove the k + 1 distant item ; Driver method to test above method
function checkDuplicatesWithinK ( arr , n , k ) { let myset = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr . includes ( arr [ i ] ) ) { return true ; } myset . add ( arr [ i ] ) ; if ( i >= k ) { index = array . indexOf ( arr [ i - k ] ) ; array . splice ( index , 1 ) ; } } return false ; } let arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ] ; let n = arr . length ; if ( checkDuplicatesWithinK ( arr , n , 3 ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }