Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Building a binary heap from n given keys: what are the worst-case costs of (i) bottom-up heapify and (ii) n successive inserts into an empty heap?

  1. A. (i) Θ(n log n), (ii) Θ(n log n)
  2. B. (i) Θ(n), (ii) Θ(n)
  3. C. (i) Θ(log n), (ii) Θ(n log n)
  4. D. (i) Θ(n), (ii) Θ(n log n)

Correct answer: D. (i) Θ(n), (ii) Θ(n log n)

Bottom-up heapify sifts down from the last internal node; about n/2^(h+1) nodes sit at height h and each costs O(h), and Σ h/2^h converges, giving Θ(n). Inserting keys in increasing order into a max-heap makes every insert sift all the way up, so n inserts cost Θ(n log n).

More Coding Interview Problems questions

Exams that ask this topic