Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?

Tags:

How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number with a complexity of nlogn?

like image 543
Bunny Rabbit Avatar asked Apr 19 '10 10:04

Bunny Rabbit


People also ask

How do you find the sum of two numbers in an array?

While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum. While adding 0th index element if the carry left, then append it to beginning of the number.

What is the algorithm of sum of two numbers?

Step 1: Start. Step 2: Read A, B. Step 3: Sum=A+B. Step 4: Print Sum.

How do you know if 2 numbers in an array are equal?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

I'm sure there's a better way, but here's an idea:

  1. Sort array
  2. For every element e in the array, binary search for the complement (sum - e)

Both these operations are O(n log n).

like image 135
Andreas Brinck Avatar answered Oct 15 '22 00:10

Andreas Brinck