ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is the time complexity of building a heap from n items with heapq.heapify, compared with pushing the n items one by one with heapq.heappush?

  1. A. Both are O(n), since the heap array is a flat list
  2. B. heapify is O(n) and n pushes cost O(n log n) in total
  3. C. Both are O(n log n) because each push sifts up through O(log n) levels
  4. D. heapify is O(n log n) and pushes are O(n)

Correct answer: B. heapify is O(n) and n pushes cost O(n log n) in total

heapify works bottom-up and does linear total work. Pushing one at a time costs O(log i) per item, which sums to O(n log n) in the worst case.

More Python Programming questions

Exams that ask this topic