Data Structures & AlgorithmsHardProduct Company SDE · heap round
Problem: What does the following print for the array [7, 10, 4, 3, 20, 15] with k = 3?
Problem: What does the following print for the array [7, 10, 4, 3, 20, 15] with k = 3?
import heapq
def kth(a, k):
h = []
for x in a:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
return h[0]
print(kth([7, 10, 4, 3, 20, 15], 3))- A. 4
- B. 7
- C. 10
- D. 15
Correct answer: C. 10
A min-heap capped at size k keeps the k largest values {10, 15, 20}, and its root 10 is the 3rd largest. Returning the root of a max-heap or the 3rd smallest value are the traps.
More Coding Interview Problems questions
- Problem: What does the following print? python ops = [('b', 2), ('a', 2), ('c', 1), ('d', 3)] print([x for x, in sorted(ops, key=lambda t…
- Problem: Coins of values {1, 5, 6, 9} are available, unlimited copies each. What is the minimum number of coins needed to make exactly 11?
- Problem: In the O(n log n) longest increasing subsequence algorithm, the array tails[k] is maintained over the input. What does tails[k]…
- Problem: A dynamic array doubles its capacity whenever it is full and copies all elements. Which statement about n pushes is correct?
- Problem: How many ways are there to tile a 2 x 10 board completely with 2 x 1 dominoes (placed horizontally or vertically)?
- Array a = [1, -1, 2, 3, -2, 4, -3, 1]. How many contiguous non-empty subarrays have sum exactly 3? Solve it with running prefix sums and a…