Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped.
Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped.
import heapq
h = []
for x in [7, 3, 9, 1, 5]:
heapq.heappush(h, x)
snap = h[:]
print(snap, heapq.heappop(h), h)What is printed?- A. [1, 3, 9, 7, 5] 1 [3, 5, 9, 7]
- B. [1, 3, 5, 7, 9] 1 [3, 5, 7, 9]
- C. [7, 3, 9, 1, 5] 1 [3, 5, 9, 7]
- D. [1, 3, 9, 7, 5] 1 [3, 9, 7, 5]
Correct answer: A. [1, 3, 9, 7, 5] 1 [3, 5, 9, 7]
A heap is only partially ordered: children of index i sit at 2i + 1 and 2i + 2. Pushes sift up: [7] → [3, 7] → [3, 7, 9] → 1 rises past 7 and 3 → [1, 3, 9, 7] → 5 is placed under 3 → [1, 3, 9, 7, 5]. Pop moves the last element 5 to the root and sifts it down below 3 → [3, 5, 9, 7]. The list is not sorted; only h[0] is guaranteed minimal. Push/pop O(log n).
More Coding Interview Problems questions
- Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1. python…
- Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component…
- Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the…
- Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.) python…
- Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed. python def…
- Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining…