Search code examples
algorithmbig-onotation

What is Big O of two nested loops?


I am trying to figure out Big O of following code:

for(let i = 0; i < arr.length; i++) {
  for(let j = 0; j < arr[i].someVariable; j++) {
    console.log("Hello world")
  }
}

arr[i].someVariable is any number from 1 to infinity.

Do you have some ideas?


Solution

  • The complexity is O(Σ Vi) where Vi is arr[i].someVariable and the sum runs over all elements of arr.

    A more intuitive expression is O(N.V) where N is the array size and V the average value of the Vi.