Algorithm to find the pair of numbers in an integer array whoes sum are equal. ex {1 2 3 4 6}
here{3 2} { 4 1} should be the output, because the sum is 3+2=5, 4+1=5.
Here the main thing is the complexity shld be O(n). Please help me if we find any solutions for 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.
In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1.
Are you sure that the problem is solvable at all in O(n)?
Imagine the case when the input sequence is just {0, 0, 0, 0, 0, 0, ..., 0}. Here every two pairs satisfy the condition. Just listing all the pairs is already at least O(n^2).
I think it's possible:
you need a second array tmp = {} with the length of sum.
sum = 5
array = {1,2,3,4,6}
for every i in array{
if i>=sum:
continue
if tmp[i] != 0 {
output {i,(sum-i)}
tmp[i] = 0
continue
}
tmp[sum-i] := i
}
that's it. so simple and with O(n)
cons:
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