Check if a given array contains duplicate elements within k distance from each other | Java 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
import java . util . * ; class Main { static boolean checkDuplicatesWithinK ( int arr [ ] , int k ) { HashSet < Integer > set = new HashSet < > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( set . contains ( arr [ i ] ) ) return true ; set . add ( arr [ i ] ) ; if ( i >= k ) set . remove ( arr [ i - k ] ) ; } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 5 , 3 , 4 , 3 , 5 , 6 } ; if ( checkDuplicatesWithinK ( arr , 3 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }