How the time complexity of the following code is O(n)?

前端 未结 1 1908
南旧
南旧 2021-01-26 09:30

I was solving a time-complexity question on Interview Bit, which is given below in the image.

The correct answer to this question is O(N). But according to me, the answe

1条回答
  •  -上瘾入骨i
    2021-01-26 10:06

    Do the actual math:

    T(N) = N + N/2 + N/4 + ... + 1 (log_2 N terms in the sum)
    

    This is a geometric series with ratio 1/2, so the sum is equal to:

    T(N) = N*[1 - (1/2)^(log_2 N)] / (1 - 1/2) =
         = [N - N/(2^log_2 N)] / 0.5 =
         2^log_2 N = N
         = (N - 1) / 0.5 
    

    So T(N) is O(N).

    0 讨论(0)
提交回复
热议问题