Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Rocks are smashed repeatedly: take the two heaviest; if equal both vanish, otherwise the difference remains. Report the last weight (0 if none), using a max-heap via negation.

Problem: Rocks are smashed repeatedly: take the two heaviest; if equal both vanish, otherwise the difference remains. Report the last weight (0 if none), using a max-heap via negation.
import heapq
def smash(stones):
    h = [-s for s in stones]; heapq.heapify(h)
    while len(h) > 1:
        a, b = -heapq.heappop(h), -heapq.heappop(h)
        if a != b: heapq.heappush(h, -(a - b))
    return -h[0] if h else 0
print(smash([6, 3, 9, 4, 1]), smash([5, 5]))
What is printed?
  1. A. 0 0
  2. B. 1 0
  3. C. 1 5
  4. D. 3 0

Correct answer: B. 1 0

Python's heapq is a min-heap, so store negatives. [6, 3, 9, 4, 1]: 9 vs 6 → 3; heap 4, 3, 3, 1: 4 vs 3 → 1; heap 3, 1, 1: 3 vs 1 → 2; heap 2, 1: → 1. [5, 5] cancels → 0. Each round is O(log n), O(n log n) total.

More Coding Interview Problems questions

Exams that ask this topic