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?
- A. Both are O(n), since the heap array is a flat list
- B. heapify is O(n) and n pushes cost O(n log n) in total
- C. Both are O(n log n) because each push sifts up through O(log n) levels
- 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
- What is printed? python x = 255 print(x.bitlength(), bin(x).count('1'), (x & -x), (x - 1) & x)
- What is printed? python print(-7 // 2, 7 // -2, -7 % 2, 7 % -2)
- What is printed? python def pairs(a, t): a = sorted(a) i, j, c = 0, len(a) - 1, 0 while i < j: s = a[i] + a[j] if s == t: c += 1 i += 1 j…
- What is printed? python def countk(a, k): pre = {0: 1} s = 0 ans = 0 for x in a: s += x ans += pre.get(s - k, 0) pre[s] = pre.get(s, 0) +…
- What is printed? python from collections import deque g = ['..#', '.##', '...'] def bfs(g): R, C = len(g), len(g[0]) d = {(0, 0): 0} q =…
- What is printed? python from functools import lrucache calls = 0 @lrucache(maxsize=None) def f(n): global calls calls += 1 if n < 2…