Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024?

Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024?
def cnt(n):
    c = 0
    for i in range(n):
        j = 1
        while j < n:
            j *= 2; c += 1
    return c
print(cnt(1024), cnt(1000))
What is printed?
  1. A. 1048576 1000000
  2. B. 10240 9000
  3. C. 2047 1999
  4. D. 10240 10000

Correct answer: D. 10240 10000

The inner loop doubles j from 1 until it reaches n: ⌈log₂ n⌉ steps (10 for both 1024 and 1000), independent of i. Total n·⌈log₂ n⌉ → O(n log n): 1024 × 10 and 1000 × 10. Treating it as O(n²) (the first wrong option) ignores the doubling.

More Coding Interview Problems questions

Exams that ask this topic