Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to find the pair of numbers in an integer array whoes sum are equal

Tags:

algorithm

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?

like image 431
sandeep Avatar asked Dec 04 '10 12:12

sandeep


People also ask

How do you find pairs in an array whose sum is equal to some number?

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.

How do you find a pair in an array?

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.


2 Answers

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).

like image 158
Vlad Avatar answered Sep 24 '22 02:09

Vlad


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:

  1. it won't find a pair like {5,0}, therefore you have to use real Integer-Objects to check at line 6 against NULL and assign NULL in line 8,
  2. pairs with a negative number won't work.
like image 40
ChaosCoder Avatar answered Sep 25 '22 02:09

ChaosCoder