Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O Notation - Is this O(n) or O(n2)?

I wrote a script that basically finds how many boxes can fit in another(bigger) box.

I have the boxes Array with all the box sizes and the products Array with the sizes of each product's box.

let boxes = [
  {label:'box1', width: 4, height: 3, length: 12},
  {label:'box2', width: 6, height: 5, length: 14},
  {label:'box3', width: 8, height: 6, length: 24},
];

let products = [
    {name:'AudioBox3000 ',  width: 2, height:  1, length: 3},
    {name:'Canister1500 ', width: 5, height:  1, length: 11}
];

for(let j = 0; j < products.length; j++)  // O(n)
{
    createDiv('********' + products[j].name + '*********');
  
    for (let i = 0; i < boxes.length; i++)  // O(m)
    {
      let totalWidth  = Math.floor(boxes[i].width  / products[j].width);
      let totalHeight = Math.floor(boxes[i].height / products[j].height);
      let totalLenght = Math.floor(boxes[i].length / products[j].length);
      let totalBoxes  = totalWidth * totalHeight * totalLenght;
      createDiv(totalBoxes + ' boxes fits on ' + boxes[i].label); 
    }
}

function createDiv (value) {
    let div = document.createElement('div');
    div.setAttribute('class', 'app');
    div.innerHTML = value;
    document.body.appendChild(div);
}
 

So is clear that for(let j = 0; j < products.length; j++) is O(n)

and for (let i = 0; i < boxes.length; i++) is also O(n)

So I'm confused if it is O(n²) or O(n).

Could you elaborate an explanation?

like image 461
German Gabriel Avatar asked Mar 04 '23 12:03

German Gabriel


1 Answers

It's neither O(n) nor O(n2).

Lets consider N as the number of products and M then number of boxes.

The time complexity of this algorithm is O(N * M).

It's important to distinguish this 2 because for instance, let's imagine that the number of boxes is a fixed number, like 100... Then M would be a constant and therefore the time complexity of the algorithm would be linear. On the other hand, if the number of boxes can be expressed as a function of the number of products, like for instance, lets imagine that the number of boxes is the number of products power 2, in that case M would be equal to N ^ 2, so the time complexity would be O(N^3).

If the number of products and the number of boxes are not related at all, and they both can grow differently, then the time complexity is definitely O(N * M).

like image 117
Josep Avatar answered Mar 08 '23 23:03

Josep