</>

1046. Last Stone Weight

Easy NeetCode 150
Heap / Priority Queue Time O(NlogN) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Heap / Priority Queue
Time
O(NlogN)
Space
O(N)

Standard Solution (C++)

SummaryGiven a collection of stone weights, repeatedly smash the two heaviest stones together: if they differ, the survivor has weight equal to the difference; if equal, both are destroyed. Return the weight of the last remaining stone, or 0 if none remain.

Approach
  • Use a max-heap (priority queue) so the two largest stones are always accessible in O(log n).
  • Each round, pop the two heaviest stones; if they differ, push the remainder back.
  • Repeat until at most one stone is left — that stone's weight (or 0) is the answer.
  • Each smash costs O(log n), and there are at most n-1 smashes, giving O(n log n) overall.
#include <vector>
#include <queue>
using namespace std;

class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
        // Max-heap: largest element is always on top
        priority_queue<int> pq(stones.begin(), stones.end());

        while (pq.size() > 1) {
            int heaviest = pq.top(); pq.pop();
            int second   = pq.top(); pq.pop();

            // Only push the remainder when the stones differ
            if (heaviest != second)
                pq.push(heaviest - second);
        }

        return pq.empty() ? 0 : pq.top();
    }
};
Time O(n log n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
        
        std::priority_queue<int> max_heap(stones.begin(), stones.end());

        int x=-1, y=-1;
        while(max_heap.size()>1){
            y=max_heap.top();
            max_heap.pop();
            x=max_heap.top();
            max_heap.pop();

            if(y>x){
                max_heap.push(y-x);
            }

        }
        if(max_heap.empty()){
            return 0;
        }
        return max_heap.top();
    }
};

// Time Complexity: O(NlogN)
// Space Complexity: O(N)
Time O(NlogN) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern