Search code examples
javascriptarraysalgorithmmemoization

Optimizing solution of Sum of Pairs: Codewars


I want a help in optimising a solution of a problem, I already sort out the problem, but my code is not good enough for handling large array - codeWars : Sum of Pairs - problem

Here is my code -

var sum_pairs=function(e, sum){

var result=null;
var arrLen=e.length;
for(let i=0;i<arrLen-1;i++){
  let nextIndex=e.slice(i+1,arrLen).indexOf(sum-e[i]);
  if(nextIndex>=0){ 
    result=[e[i],e[nextIndex+1+i]];
    arrLen=nextIndex+1+i; 
  }
}
return result;
}

Well, I know this is not a good solution. Anyway, this passes all the test cases but failed when it encounter large array - Result On codewars

I want to know how to optimise this code, and also Learn any technique to writing a good code.


Solution

  • One solution is to use Set data structure to memorize the numbers all ready iterated over. Then we can check for each element if there has been a number which sums to s. The set has an average constant time complexity for insert and search making the algorithm linear in time (and space).

    var sum_pairs=function(ints, s){
      if (ints.length < 2) return undefined; //not enough numbers for pair.
      let intSet = new Set()
      intSet.add(ints[0]);
      for (let i=1; i < ints.length; ++i){
        let needed = s-ints[i];
        if (intSet.has(needed)){//check if we have already seen the number needed to complete the pair.
          return [needed,ints[i]];
        }
        intSet.add(ints[i]);//if not insert the number in set and continue.
      }
      return undefined;//No answer found
    }