Wednesday, 13 January 2021

Is there a way to avoid number to string coonversion & nested loops for performance?

I just took a coding test online and this one question really bothered me, my solution was correct but was rejected for being unoptimized. The question is as following:

Write a function combineTheGivenNumber taking two arguments:

  1. numArray: number[]
  2. num: a number

The function should check all the concatenation pairs that can result in making a number equal to num and return there count

E.g if numArray = [1, 212, 12, 12] & num = 1212 then we will have return value of 3 from combineTheGivenNumber

There pairs are as following:

  1. numArray[0]+numArray[1]
  2. numArray[2]+numArray[3]
  3. numArray[3]+numArray[2]

The function I wrote for this purpose is as following:

function combineTheGivenNumber(numArray, num) {
  //convert all numbers to strings for easy concatenation
  numArray = numArray.map(e => e+'');
  //also convert the `hay` to string for easy comparison
  num = num+'';
  let pairCounts = 0;
  
  // itereate over the array to get pairs
  numArray.forEach((e,i) => {
    numArray.forEach((f,j) => {
    if(i!==j && num === (e+f)) {
        pairCounts++;
       }
    });
  });
  
  return pairCounts;
}

console.log('Test 1: ', combineTheGivenNumber([1,212,12,12],1212)); 

console.log('Test 2: ', combineTheGivenNumber([4,21,42,1],421)); 

From my experience, I know conversion of number to string is slow in JS, but I am not sure whether my approach is worng/lack of knowledge or does the tester is ignorant of this fact. Can anyone suggest further optimization of the code snipped? Elimination of string to number to string will be a significant speed boost but I am not sure how to check for concatenated numbers otherwise.



from Is there a way to avoid number to string coonversion & nested loops for performance?

No comments:

Post a Comment