Data Structures & AlgorithmsHardProduct Company SDE · greedy heap round
Problem: Merging ropes of lengths 2, 3, 4 costs the sum of the two lengths merged each time, always merging the two shortest. What is the total cost? Run the heap code.
Problem: Merging ropes of lengths 2, 3, 4 costs the sum of the two lengths merged each time, always merging the two shortest. What is the total cost? Run the heap code.
import heapq
h = [4, 3, 2]
heapq.heapify(h)
c = 0
while len(h) > 1:
x = heapq.heappop(h)
y = heapq.heappop(h)
c += x + y
heapq.heappush(h, x + y)
print(c)What is printed?- A. 16
- B. 9
- C. 14
- D. 5
Correct answer: C. 14
Merging 2 and 3 costs 5, then 4 and 5 cost 9, for 14. Merging the two largest first (3 + 4, then 7 + 2) costs 16, reporting only the final rope length gives 9, and a loop bound of len(h) > 2 stops after the first merge (5).
More Coding Interview Problems questions
- Problem: How many subsets (including the empty one) of {1, 2, 3, 4, 5} have a sum divisible by 4? Run the code. python print(sum(1 for m…
- Problem: What does the following print? It takes the maximum of every window of size 2 in [4, 2, 12, 11, -5]. python a = [4, 2, 12, 11…
- Problem: What is the sum of the number of 1-bits in the binary representations of 1, 2, ..., 20? Run the code. python…
- Problem: Which statement about shortest paths in a weighted directed acyclic graph (DAG) is correct?
- Problem: Which statement about Floyd-Warshall on a graph with V = 400 vertices and no negative cycles is correct?
- Problem: Minimum number of taps needed to water a garden of length 5 is found from tap i covering [i - ri, i + ri]. Here n = 5 and r = [3…