Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (min-heap array after inserts)
What is printed? (min-heap array after inserts)
import heapq
h = []
for x in [9, 4, 7, 1, 8, 2]:
heapq.heappush(h, x)
print(h, heapq.heappop(h), h)- A. [1, 4, 2, 9, 8, 7] 1 [2, 4, 7, 9, 8]
- B. [1, 2, 4, 7, 8, 9] 1 [2, 4, 7, 8, 9]
- C. [2, 4, 7, 8, 9] 1 [2, 4, 7, 8, 9]
- D. [2, 4, 7, 9, 8] 1 [2, 4, 7, 9, 8]
Correct answer: D. [2, 4, 7, 9, 8] 1 [2, 4, 7, 9, 8]
After the six pushes the heap array is [1, 4, 2, 9, 8, 7] (a heap, not a sorted list). But print's arguments are all evaluated before anything is printed, and both h arguments are the same list object – heappop has already moved 7 to the root and sifted it below 2, so both show [2, 4, 7, 9, 8]. Push and pop are O(log n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (queue using a fixed array without wrap-around) python N = 4; q = [None] N; front = rear = 0; log = [] def enq(x): global…
- A warehouse scores a shelf by adding, over every contiguous run of boxes, the weight of the lightest box in the run. Two monotonic-stack…
- A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed? python from collections…
- atmost(s, k) counts substrings with at most k distinct letters using a sliding window and a frequency map. What is printed? python def…
- A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed? python def prefix(p): pi = [0] len(p) for i in…
- Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed? python def z(s): n = len(s); z = [0] n; l = r = 0…