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?- A. 0 0
- B. 1 0
- C. 1 5
- 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
- Problem: Room 0 is open; each room holds keys to other rooms. Can every room be visited? (DFS over keys.) python def canvisitall(rooms)…
- Problem: Traverse a small directed graph (adjacency lists in the order shown) from node 0, once with recursive DFS and once with BFS…
- Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped. python import…
- Problem: Each element of a log is at most k = 2 positions away from its sorted position. Sort it with a min-heap of size k + 1. python…
- Problem: Is an undirected graph with n nodes a tree? Check edge count = n − 1 and that union-find never sees an edge inside one component…
- Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the…