Count distinct elements in every window of size k | Simple Python3 program to count distinct elements in every window of size k ; Counts distinct elements in window of size k ; Traverse the window ; Check if element arr [ i ] exists in arr [ 0. . i - 1 ] ; Counts distinct elements in all windows of size k ; Traverse through every window ; Driver Code
import math as mt NEW_LINE def countWindowDistinct ( win , k ) : NEW_LINE INDENT dist_count = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT j = 0 NEW_LINE while j < i : NEW_LINE INDENT if ( win [ i ] == win [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT if ( j == i ) : NEW_LINE INDENT dist_count += 1 NEW_LINE DEDENT DEDENT return dist_count NEW_LINE DEDENT def countDistinct ( arr , n , k ) : NEW_LINE INDENT for i in range ( n - k + 1 ) : NEW_LINE INDENT print ( countWindowDistinct ( arr [ i : k + i ] , k ) ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 1 , 3 , 4 , 2 , 3 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE countDistinct ( arr , n , k ) NEW_LINE