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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit