Check if a given array contains duplicate elements within k distance from each other | C # 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 code
using System ; using System . Collections . Generic ; class GFG { static bool checkDuplicatesWithinK ( int [ ] arr , int k ) { HashSet < int > set = new HashSet < int > ( ) ; 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 ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }