Count pairs in an array such that the absolute difference between them is ÃƒÆ ’ Ã † â €™ Ãƒâ € Ã ¢ â ‚¬ â „¢ ÃƒÆ ’ Ã ¢ â ‚¬ Ãƒ ¢ Ã ¢ â € š ¬ Ã ¢ â € ž ¢ ÃƒÆ ’ Ã † â €™ Ãƒ ¢ Ã ¢ â € š ¬ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â ‚¬ Å ¡¬ Ãƒ ¢ Ã ¢ â ‚¬ Å ¾¢ ÃƒÆ ’ Ã † â €™ Ãƒâ € Ã ¢ â ‚¬ â „¢ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â ‚¬ Å ¡¬ ÃƒÆ ’ Ã † â €™¢ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â € š ¬ Ã …¡¬ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â € š ¬ Ã …¾¢¢ ÃƒÆ ’ Ã † â €™ Ãƒâ € Ã ¢ â ‚¬ â „¢ ÃƒÆ ’ Ã ¢ â ‚¬ Ãƒ ¢ Ã ¢ â € š ¬ Ã ¢ â € ž ¢ ÃƒÆ ’ Ã † â €™ Ãƒ ¢ Ã ¢ â € š ¬ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â ‚¬ Å ¡¬ Ãƒ ¢ Ã ¢ â ‚¬ Å ¾¢¢ ÃƒÆ ’ Ã † â €™ Ãƒâ € Ã ¢ â ‚¬ â „¢ ÃƒÆ ’ Ã ¢ â ‚¬ Ãƒ ¢ Ã ¢ â € š ¬ Ã ¢ â € ž ¢¢ ÃƒÆ ’ Ã † â €™ Ãƒâ € Ã ¢ â ‚¬ â „¢¢ ÃƒÆ ’ Ã † â €™¢ ÃƒÆ ’¢ Ãƒ ¢ Ã ¢ â ‚¬ Å ¡¬ Ãƒâ €¦¡¬ ÃƒÆ ’ Ã † â €™ Ãƒ ¢ Ã ¢ â € š ¬¦¡¬°¥ K | ''Function to return the count of required pairs ; '' Sort the given array ; ''To store the required count ; ''Update j such that it is always > i ; '' Find the first element arr[j] such that  (arr[j] - arr[i]) >= K  This is because after this element, all the elements will have absolute difference  with arr[i] >= k and the count of  valid pairs will be (n - j) ; '' Update the count of valid pairs ; '' Get to the next element to repeat the steps ; '' Return the count ; ''Driver code
def count ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE cnt = 0 ; NEW_LINE DEDENT i = 0 ; j = 1 ; NEW_LINE INDENT while ( i < n and j < n ) : NEW_LINE if j <= i : NEW_LINE j = i + 1 NEW_LINE else : NEW_LINE j = j NEW_LINE while ( j < n and ( arr [ j ] - arr [ i ] ) < k ) : NEW_LINE j += 1 ; NEW_LINE cnt += ( n - j ) ; NEW_LINE DEDENT i += 1 ; NEW_LINE INDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( count ( arr , n , k ) ) ; NEW_LINE DEDENT