Count distinct elements from a range of a sorted sequence from a given frequency array | Function to find the first index with value is at least element ; Update the value of left ; Binary search for the element ; Find the middle element ; Check if the value lies between the elements at index mid - 1 and mid ; Check in the right subarray ; Update the value of left ; Check in left subarray ; Update the value of right ; Function to count the number of distinct elements over the range [ L , R ] in the sorted sequence ; Stores the count of distinct elements ; Create the prefix sum array ; Update the value of count ; Update the value of pref [ i ] ; Calculating the first index of L and R using binary search ; Print the resultant count ; Driver Code
def binarysearch ( array , right , element ) : NEW_LINE INDENT left = 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right // 2 ) NEW_LINE if ( array [ mid ] == element ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid - 1 > 0 and array [ mid ] > element and array [ mid - 1 ] < element ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( array [ mid ] < element ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def countDistinct ( arr , L , R ) : NEW_LINE INDENT count = 0 NEW_LINE pref = [ 0 ] * ( len ( arr ) + 1 ) NEW_LINE for i in range ( 1 , len ( arr ) + 1 ) : NEW_LINE INDENT count += arr [ i - 1 ] NEW_LINE pref [ i ] = count NEW_LINE DEDENT left = binarysearch ( pref , len ( arr ) + 1 , L ) NEW_LINE right = binarysearch ( pref , len ( arr ) + 1 , R ) NEW_LINE print ( right - left + 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 6 , 7 , 1 , 8 ] NEW_LINE L = 3 NEW_LINE R = 7 NEW_LINE countDistinct ( arr , L , R ) NEW_LINE DEDENT