Given an array of integers find the number of all ordered pairs of elements in the array whose sum lies in a given range [a,b]
Here is an O(n^2) solution for the same
'''
counts all pairs in array such that the
sum of pair lies in the range a and b
'''
def countpairs(array, a, b):
num_of_pairs = 0
for i in range(len(array)):
for j in range(i+1,len(array)):
total = array[i] + array[j]
if total >= a and total <= b:
num_of_pairs += 1
return num_of_pairs
I know my solution is not optimal What is a better algorithm for doing this.
Follow the steps below to solve the given problem: Initialize the count variable with 0 which stores the result. Iterate arr and if the sum of ith and jth [i + 1…..n – 1] element is equal to sum i.e. arr[i] + arr[j] == sum, then increment the count variable. Return the count.
The time complexity is of course output-sensitive, but this is still superior to the existing algo:
O(nlogn) + O(k)
where k is the number of pairs that satisfy the condition.
Note: If you only need to count the number of pairs, you can do it in O(nlogn)
. Modify the above algorithm so [b - x] (or the next smaller element) is also searched for. This way, you can count the number of 'matches' each element has in O(logn)
simply from the indices of the first and last match. Then it's just a question of summing those up to get the final count. This way, the initial O(nlogn)
sorting step is dominant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With