EASY NC#65 Heap / Priority Queue
1046. Last Stone Weight
๐ Problem
You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is: - If x == y, both stones are destroyed - If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone. If there are no stones left, return 0.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
- โขApply Heap reasoning pattern
- โขApply Backtracking reasoning pattern
๐ก Approach
- โ Use max heap to always get two heaviest stones
- โ Simulate smashing until 0 or 1 stones remain
- โ In TypeScript, use min heap with negation for max heap
- โ Time: O(n log n), Space: O(n)
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse max heap to always get two heaviest stones
- โขSimulate smashing until 0 or 1 stones remain
- โขIn TypeScript, use min heap with negation for max heap
Common Pitfalls
- โขTime: O(n log n), Space: O(n)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
lastStoneWeight([2,7,4,1,8,1]); Expected:
1 Test Case 2
Not run Input:
lastStoneWeight([1]); Expected:
1 Test Case 3
Not run Input:
lastStoneWeight([10,10]); Expected:
0 ๐ Code Editor
๐ค Output