Ashton Hauser
Ashton Hauser

Reputation: 111

Trying to optimize my code to either remove nested loop or make it more efficient

Have found the solution to this Kata from Code Wars but it times out (After 12 seconds) in the editor when I run it; any ideas as too how I should further optimize the nested for loop and or remove it?

function removeNb(n) {
  var nArray = [];
  var sum = 0;
  var answersArray = [];
  for (let i = 1; i <= n; i++) {
    nArray.push(n - (n - i));
    sum += i;
  }
  var length = nArray.length;
  for (let i = Math.round(n / 2); i < length; i++) {
    for (let y = Math.round(n / 2); y < length; y++) {
      if (i != y) {
        if (i * y === sum - i - y) {
          answersArray.push([i, y]);
          break;
        }
      }
    }
  }
  return answersArray;
}

console.log(removeNb(102));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 8

Views: 1304

Answers (5)

Myndex
Myndex

Reputation: 5364

This is part comment, part answer.

In engineering terms, the original function posted is using "brute force" to solve the problem, iterating every (or more than needed) possible combinations. The number of iterations is n is large - if you did all possible it would be

n * (n-1) = bazillio n

Less is More

So lets look at things that can be optimized, first some minor things, I'm a little confused about the first for loop and nArray:

// OP's code
 for(let i = 1; i <= n; i++) {
    nArray.push(n - (n - i));
    sum += i;
  }

??? You don't really use nArray for anything? Length is just n .. am I so sleep deprived I'm missing something? And while you can sum a consecutive sequence of integers 1-n by using a for loop, there is a direct and easy way that avoids a loop:

sum = ( n + 1 ) * n * 0.5 ;

THE LOOPS

   // OP's loops, not optimized
for(let i = Math.round(n/2); i < length; i++) {
    for(let y = Math.round(n/2); y < length; y++) {
      if(i != y) {
        if(i*y === sum - i - y) {

Optimization Considerations:

I see you're on the right track in a way, cutting the starting i, y values in half since the factors . But you're iterating both of them in the same direction : UP. And also, the lower numbers look like they can go a little below half of n (perhaps not because the sequence start at 1, I haven't confirmed that, but it seems the case).

Plus we want to avoid division every time we start an instantiation of the loop (i.e set the variable once, and also we're going to change it). And finally, with the IF statements, i and y will never be equal to each other the way we're going to create the loops, so that's a conditional that can vanish.

But the more important thing is the direction of transversing the loops. The smaller factor low is probably going to be close to the lowest loop value (about half of n) and the larger factor hi is probably going to be near the value of n. If we has some solid math theory that said something like "hi will never be less than 0.75n" then we could make a couple mods to take advantage of that knowledge.

The way the loops are show below, they break and iterate before the hi and low loops meet.

Moreover, it doesn't matter which loop picks the lower or higher number, so we can use this to shorten the inner loop as number pairs are tested, making the loop smaller each time. We don't want to waste time checking the same pair of numbers more than once! The lower factor's loop will start a little below half of n and go up, and the higher factor's loop will start at n and go down.

// Code Fragment, more optimized:

let nHi = n;
let low = Math.trunc( n * 0.49 );
let sum = ( n + 1 ) * n * 0.5 ;

                    // While Loop for the outside (incrementing) loop
while( low < nHi ) {
                                       // FOR loop for the inside decrementing loop
    for(let hi = nHi; hi > low; hi--) {
                                        // If we're higher than the sum, we exit, decrement.
        if( hi * low + hi + low > sum ) { 
            continue; 
        }
                                               // If we're equal, then we're DONE and we write to array.
        else if( hi * low + hi + low === sum) {
            answersArray.push([hi, low]);
            low = nHi; // Note this is if we want to end once finding one pair
            break; // If you want to find ALL pairs for large numbers then replace these low = nHi; with low++;
        } 
               // And if not, we increment the low counter and restart the hi loop from the top.
        else {
            low++;
            break;
        }
    } // close for
} // close while

Tutorial:

So we set the few variables. Note that low is set slightly less than half of n, as larger numbers look like they could be a few points less. Also, we don't round, we truncate, which is essentially "always rounding down", and is slightly better for performance, (though it dosenit matter in this instance with just the single assignment).

The while loop starts at the lowest value and increments, potentially all the way up to n-1. The hi FOR loop starts at n (copied to nHi), and then decrements until the factor are found OR it intercepts at low + 1.

The conditionals: First IF: If we're higher than the sum, we exit, decrement, and continue at a lower value for the hi factor. ELSE IF: If we are EQUAL, then we're done, and break for lunch. We set low = nHi so that when we break out of the FOR loop, we will also exit the WHILE loop. ELSE: If we get here it's because we're less than the sum, so we need to increment the while loop and reset the hi FOR loop to start again from n (nHi).

Upvotes: 0

גלעד ברקן
גלעד ברקן

Reputation: 23955

In case it's of interest, CY Aries pointed this out:

ab + a + b = n(n + 1)/2

add 1 to both sides

ab + a + b + 1 = (n^2 + n + 2) / 2
(a + 1)(b + 1) = (n^2 + n + 2) / 2

so we're looking for factors of (n^2 + n + 2) / 2 and have some indication about the least size of the factor. This doesn't necessarily imply a great improvement in complexity for the actual search but still it's kind of cool.

Upvotes: 0

eddiewould
eddiewould

Reputation: 1633

Hassan is correct, here is a full solution:

function removeNb (n) {
  var a = 1;
  var d = 1;

  // Calculate the sum of the numbers 1-n without anything removed
  var S = 0.5 * n * (2*a + (d *(n-1)));

  // For each possible value of b, calculate a if it exists.
  var results =  [];
  for (let numB = a; numB <= n; numB++) {
      let eq1 = S - numB;
      let eq2 = numB + 1;
      if (eq1 % eq2 === 0) {
          let numA = eq1 / eq2;
          if (numA < n && numA != numB) {
              results.push([numA, numB]);
              results.push([numB, numA]);
          }
      }
  }

  return results;
}

Upvotes: 0

bkoodaa
bkoodaa

Reputation: 5361

You can solve this in linear time with two pointers method (page 77 in the book).

In order to gain intuition towards a solution, let's start thinking about this part of your code:

for(let i = Math.round(n/2); i < length; i++) {
    for(let y = Math.round(n/2); y < length; y++) {
        ...

You already figured out this is the part of your code that is slow. You are trying every combination of i and y, but what if you didn't have to try every single combination?

Let's take a small example to illustrate why you don't have to try every combination.

Suppose n == 10 so we have 1 2 3 4 5 6 7 8 9 10 where sum = 55.

Suppose the first combination we tried was 1*10.

Does it make sense to try 1*9 next? Of course not, since we know that 1*10 < 55-10-1 we know we have to increase our product, not decrease it.

So let's try 2*10. Well, 20 < 55-10-2 so we still have to increase.

3*10==30 < 55-3-10==42

4*10==40 < 55-4-10==41

But then 5*10==50 > 55-5-10==40. Now we know we have to decrease our product. We could either decrease 5 or we could decrease 10, but we already know that there is no solution if we decrease 5 (since we tried that in the previous step). So the only choice is to decrease 10.

5*9==45 > 55-5-9==41. Same thing again: we have to decrease 9.

5*8==40 < 55-5-8==42. And now we have to increase again...


You can think about the above example as having 2 pointers which are initialized to the beginning and end of the sequence. At every step we either

  • move the left pointer towards right
  • or move the right pointer towards left

In the beginning the difference between pointers is n-1. At every step the difference between pointers decreases by one. We can stop when the pointers cross each other (and say that no solution can be obtained if one was not found so far). So clearly we can not do more than n computations before arriving at a solution. This is what it means to say that the solution is linear with respect to n; no matter how large n grows, we never do more than n computations. Contrast this to your original solution, where we actually end up doing n^2 computations as n grows large.

Upvotes: 6

Hassan Saleh
Hassan Saleh

Reputation: 984

I think there is no reason for calculating the sum after you fill the array, you can do that while filling it.

function removeNb(n) {
    let nArray = [];
    let sum = 0;
    for(let i = 1; i <= n; i++) {
        nArray.push(i);
        sum += i;
    }
}

And since there could be only two numbers a and b as the inputs for the formula a * b = sum - a - b, there could be only one possible value for each of them. So, there's no need to continue the loop when you find them.

if(i*y === sum - i - y) {
    answersArray.push([i,y]);
    break;
}

I recommend looking at the problem in another way.

You are trying to find two numbers a and b using this formula a * b = sum - a - b.

Why not reduce the formula like this:

a * b + a = sum - b

a ( b + 1 ) = sum - b

a = (sum - b) / ( b + 1 )

Then you only need one for loop that produces the value of b, check if (sum - b) is divisible by ( b + 1 ) and if the division produces a number that is less than n.

for(let i = 1; i <= n; i++) {
    let eq1 = sum - i;
    let eq2 = i + 1;
    if (eq1 % eq2 === 0) {
        let a = eq1 / eq2;
        if (a < n && a != i) {
            return [[a, b], [b, a]];
        }
    }
}

Upvotes: 10

Related Questions