Check if a given array contains duplicate elements within k distance from each other | Python 3 program to Check if a given array contains duplicate elements within k distance from each other ; Creates an empty list ; 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
def checkDuplicatesWithinK ( arr , n , k ) : NEW_LINE INDENT myset = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in myset : NEW_LINE INDENT return True NEW_LINE DEDENT myset . append ( arr [ i ] ) NEW_LINE if ( i >= k ) : NEW_LINE INDENT myset . remove ( arr [ i - k ] ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if ( checkDuplicatesWithinK ( arr , n , 3 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT