CodeArchon

easyHeap / Priority QueueAmazonGoogle

Boulder Showdown Arena

Two heaviest boulders are hurled at each other every round. Equal weights annihilate; unequal weights leave a fragment that re-enters the arena.

Given an array of positive integer stone weights, repeatedly smash the two heaviest. Return the weight of the last remaining stone (or 0).

Choose approach

8
7
4
1
2
1
1/9
Narrationstep 1 of 9

Build initial max-heap from stones.

1import heapq
2def lastStoneWeight(stones):
3 h = [-s for s in stones]; heapq.heapify(h)
4 while len(h) > 1:
5 a = -heapq.heappop(h); b = -heapq.heappop(h)
6 if a != b: heapq.heappush(h, -(a - b))
7 return -h[0] if h else 0
Variables
size=6

How to think about it

  1. Max-heap gives O(log n) access to the two heaviest each round.
  2. Equal weights -> both destroyed, nothing re-enters.
  3. Unequal -> only the diff re-enters.

Edge cases to catch in interview

  • Single stone -> return itself.
  • All equal pairs cancel out -> return 0.

Examples

Example 11
{"stones":[2,7,4,1,8,1]}
Example 21
{"stones":[1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed