Confused about the inner loop

A reader asked us the following question:

The outer loop is O(logn), so the inner loop would be O(n*logn)?

The complexity of this algorithm cannot be O(log(n)) because here inner loop runs var times, not n times. So when we sum the var values for all the iterations of the outer loop we will get:


Put 2^k = n Since n>2^k


The inner loop will run 2n-1 times in total (Considering all the iterations of the outer loop), and the outer loop will run log(n) times. So the overall complexity will be



When the counter variable of the inner loop is dependent on the value of the outer loop counter variable, we calculate the complexities in a different way. We will calculate the individual complexity of the inner and outer loop and then sum the overall complexity. Keeping this concept in mind, we will calculate the complexities of such algorithms.


Hey Maida_ljiaz,
I share the same thought as coderust. The inner loop is repeated LogN, besides its inside runs of N.
Therefore it should be NLogN times…making the Big O(NLogN) the considered answer.

1 Like