Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost.
Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost.
import heapq
def cost(r):
heapq.heapify(r); total = 0
while len(r) > 1:
s = heapq.heappop(r) + heapq.heappop(r)
total += s; heapq.heappush(r, s)
return total
print(cost([4, 3, 2, 6]), cost([7]))What is printed?- A. 25 0
- B. 29 0
- C. 29 7
- D. 35 0
Correct answer: B. 29 0
Always join the two shortest (Huffman-style greedy): 2+3 = 5, 4+5 = 9, 6+9 = 15; total 5 + 9 + 15 = 29. Joining in the given order costs 7 + 13 + 19 = 39 – longer ropes get added repeatedly. A single rope costs nothing. O(n log n).
More Coding Interview Problems questions
- Problem: Return the k points closest to the origin (ties broken by smaller index). python import heapq pts = [(3, 3), (5, -1), (-2, 4)…
- Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time. python…
- Problem: Merge overlapping booking intervals. python def merge(iv): iv.sort(); out = [] for s, e in iv: if out and s <= out[-1][1]…
- Problem: Remove the fewest meetings so that the rest do not overlap (meetings that only touch at an endpoint are fine). python def…
- Problem: Find the minimum number of meeting rooms needed for a list of meetings [start, end). python import heapq def rooms(iv)…
- Problem: A car starts with an empty tank at one of n petrol pumps on a circular route; pump i gives gas[i] and the trip to the next costs…