Count pairs from a given array whose sum lies from a given range | Python3 program for the above approach ; Function to count pairs whose sum lies over the range [ L , R ] ; Sort the given array ; Iterate until right > 0 ; Starting index of element whose sum with arr [ right ] >= L ; Ending index of element whose sum with arr [ right ] <= R ; Update the value of end ; Add the count of elements to the variable count ; Return the value of count ; Driver Code
from bisect import bisect_left , bisect_right NEW_LINE def countPairSum ( arr , L , R , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE right = N - 1 NEW_LINE count = 0 NEW_LINE while ( right > 0 ) : NEW_LINE INDENT it1 = bisect_left ( arr , L - arr [ right ] ) NEW_LINE start = it1 NEW_LINE it2 = bisect_right ( arr , R - arr [ right ] ) NEW_LINE it2 -= 1 NEW_LINE end = it2 NEW_LINE end = min ( end , right - 1 ) NEW_LINE if ( end - start >= 0 ) : NEW_LINE INDENT count += ( end - start + 1 ) NEW_LINE DEDENT right -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 1 , 2 , 4 , 3 ] NEW_LINE L = 5 NEW_LINE R = 8 NEW_LINE N = len ( arr ) NEW_LINE print ( countPairSum ( arr , L , R , N ) ) NEW_LINE DEDENT