Data Structures & AlgorithmsHardGATE CS · competitive programming

For (i = 1; i < n; i *= 2) and, inside it, (j = 0; j < i; j++), with n = 1024, how many times does the inner body run in total?

  1. A. 1024
  2. B. 2047
  3. C. 1023
  4. D. 512

Correct answer: C. 1023

i takes the values 1, 2, 4, …, 512, so the inner loop runs 1 + 2 + … + 512 = 1023 times. The total is O(n), not O(n log n).

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

Exams that ask this topic