joe blow
joe blow

Reputation: 45

javascript optimization for pair finding algorithm

I am working on a javascript function which takes an array of integers and a target as arguments. The task is to find the first pair of integers in the array whose sum is equal to the target. I have tried this several different ways, but I keep getting a timeout error for larger input arrays. Can someone please give me some pointers on how to better optimize this code? Thanks!

var sum_pairs = function(ints, s){
  var r = [];
  var a = true;
  var l = ints.length;
  for(var j = 0; j < l; j++){
    if(a){
      for(var i = 0; i < j; i++){
        if(ints[j] + ints[i] == s){
          r[0] = ints[i];
          r[1] = ints[j];
          a = false;
          break;
        }
      }
    }
    else{
      console.log('breaking');
      break;
    }
  }
return r[0] == null ? null : r;
}

Upvotes: 3

Views: 380

Answers (2)

le_m
le_m

Reputation: 20238

For each number that we encounter while iterating the array, we add that number's expected partner target - number into a Set. As soon as we encounter a number that is already in our set, we know that its partner has already been encountered and return this pair as the solution:

// Return the first two values of 'numbers' summing up to 'target':
function sum_pairs(numbers, target) {
  let paired = new Set();
  for (let number of numbers) {
    if (paired.has(number)) return [target - number, number];
    paired.add(target - number);
  }
}

// Examples:
console.log(...sum_pairs([9, 3, 7, 5, 1], 10)); // [3, 7]
console.log(...sum_pairs([4, 3, 2, 3, 4],  6)); // [4, 2]
console.log(...sum_pairs([9, 3, 6, 4, 1], 10)); // [6, 4]

This implementation has a linear runtime complexity and is therefore faster for long input arrays, but it comes with an additional memory cost.

If you are going for raw speed, replace the for-of loop with a traditional for-loop and the let variable binding with a var declaration.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You could use some speeding mechanisms, like

  • single loop,
  • hash table for visited values
  • variable a for element array[i]
  • very short variable names (just kidding)

Long list needs 153 ms.

var sum_pairs = function (array, s) {
    var a, i,
        hash = Object.create(null);

    for (i = 0; i < array.length; i++) {
        a = array[i];
        if (hash[s - a]) {
            return [s - a, a];
        }
        if (!hash[a]) {
            hash[a] = true;
        }
    }
};

console.log(sum_pairs([11, 3, 7, 5], 10));        // [3, 7]
console.log(sum_pairs([4, 3, 2, 3, 4], 6));       // [4, 2]
console.log(sum_pairs([0, 0, -2, 3], 2));         // undefined
console.log(sum_pairs([10, 5, 2, 3, 7, 5], 10));  // [3, 7]
console.log(sum_pairs([1, 2, 3, 4, 1, 0], 2));    // [1, 1]
console.log(sum_pairs([1, -2, 3, 0, -6, 1], -6)); // [0, -6]
console.log(sum_pairs([0, 2, 0], 0));             // [0, 0]
console.log(sum_pairs([5, 9, 13, -3], 10));       // [13, -3]
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions