Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming Interview Question / how to find if any two integers in an array sum to zero?

Tags:

algorithm

Not a homework question, but a possible interview question...

  1. Given an array of integers, write an algorithm that will check if the sum of any two is zero.
  2. What is the Big O of this solution?

Looking for non brute force methods

like image 643
MetaCarpal Avatar asked Jun 29 '10 08:06

MetaCarpal


People also ask

How do you find all pairs of elements in an array whose sum is equal to given 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 all pairs of an integer array whose sum is equal to a given number JS?

Write a JavaScript program to find a pair of elements (indices of the two numbers) from an given array whose sum equals a specific target number. ES6 Version: function twoSum(nums, target_num) { const map = []; const indexnum = []; for (let x = 0; x < nums. length; x++) { if (map[nums[x]] !=


2 Answers

Use a lookup table: Scan through the array, inserting all positive values into the table. If you encounter a negative value of the same magnitude (which you can easily lookup in the table); the sum of them will be zero. The lookup table can be a hashtable to conserve memory.

This solution should be O(N).

Pseudo code:

var table = new HashSet<int>();
var array = // your int array
foreach(int n in array)
{
     if ( !table.Contains(n) ) 
         table.Add(n);
     if ( table.Contains(n*-1) )
         // You found it.;
}
like image 103
driis Avatar answered Sep 25 '22 13:09

driis


The hashtable solution others have mentioned is usually O(n), but it can also degenerate to O(n^2) in theory.

Here's a Theta(n log n) solution that never degenerates:

Sort the array (optimal quicksort, heap sort, merge sort are all Theta(n log n))
for i = 1, array.len - 1
    binary search for -array[i] in i+1, array.len

If your binary search ever returns true, then you can stop the algorithm and you have a solution.

like image 26
IVlad Avatar answered Sep 26 '22 13:09

IVlad