-3

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?

greybeard
  • 2,249
  • 8
  • 30
  • 66
karolinski
  • 577
  • 1
  • 6
  • 18
  • 3
    Impossible to say without knowing anything about `arr[i].someVariable` – derpirscher May 28 '22 at 17:12
  • it is any number, from 1 to infinity – karolinski May 28 '22 at 17:12
  • Then Big O can be anything in between `array.length` (ie `n`) and `infinity` – derpirscher May 28 '22 at 17:16
  • I am not sure about that, hmmm – karolinski May 28 '22 at 17:19
  • Well, what would you expect as answer, based on your description. The only thing that is for sure, is that the outer loop is executed `array.lenth` times. We don't know whether all of the `arr[i].somevalue` are constant or not, or if they depend on the length of the array or anything else. So there is no way of determining a sensible value for Big O – derpirscher May 28 '22 at 17:20
  • someVariable is constant value, it doesn't change, but it can be different for given index – karolinski May 28 '22 at 17:22
  • 1
    Then it's O(n) ... Or you can also say it's O( n * m), where m is the maximum of someVariable. But as that is constant, it doesn't matter, thus it's again O(n) – derpirscher May 28 '22 at 17:23
  • Does the value of `arr[i].someVariable` increase as `i` increases? – k314159 May 31 '22 at 16:19
  • @derpirscher: the quote "any number from 1 to infinity" leaves room for unbounded values. –  May 31 '22 at 17:21

1 Answers1

2

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.