Data Structures & AlgorithmsHardProduct-company MCQ pattern

What is the time complexity of this code fragment?

What is the time complexity of this code fragment?
int count = 0;
for (int i = 1; i < n; i *= 2)
    for (int j = 0; j < i; j++)
        count++;
  1. A. O(n)
  2. B. O(n log n)
  3. C. O(n²)
  4. D. O(log n)

Correct answer: A. O(n)

The inner loop runs 1 + 2 + 4 + … up to below n times, a geometric series under 2n (for n = 1024 it is exactly 1023), so the total is O(n). O(n log n) comes from wrongly multiplying log n outer iterations by n.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic