BackendML

Last Stone Weight

Easy2 min read
The Last Stone Weight problem requires repeatedly selecting the two heaviest stones and determining the weight of the stone that remains after they collide.

Problem

Given an array of integers stones, where each value represents the weight of a stone, repeatedly perform the following operation:

Choose the two heaviest stones and smash them together. If the stones have equal weight, both stones are destroyed. Otherwise, the heavier stone remains with a weight equal to the difference between the two stones.

Return the weight of the last remaining stone. If no stones remain, return 0.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
stones = [2,7,4,1,8,1]
Output
1

Example 2

Input
stones = [1]
Output
1

Solution

This solution uses a Max Heap to efficiently retrieve the two heaviest stones. Java's PriorityQueue is a min heap by default, so we provide Collections.reverseOrder() to create a max heap.

We repeatedly remove the two largest stones from the heap. If their weights are different, we insert the difference back into the heap. When fewer than two stones remain, the remaining stone is the answer.
class Solution {
    public int lastStoneWeight(int[] stones) {
        PriorityQueue<Integer> maxHeap =
                new PriorityQueue<>(Collections.reverseOrder());

        for (int stone : stones) {
            maxHeap.offer(stone);
        }

        while (maxHeap.size() > 1) {
            int first = maxHeap.poll();
            int second = maxHeap.poll();

            if (first != second) {
                maxHeap.offer(first - second);
            }
        }
        return maxHeap.isEmpty() ? 0 : maxHeap.peek();
    }
}

Complexity

Building the heap takes O(n) time. Each stone can be removed and inserted into the heap multiple times, with each heap operation taking O(log n). Therefore, the overall time complexity is O(n log n).

The max heap stores up to n stones, so the extra space complexity is O(n).

Comments

No comments yet. Ask a question or share what helped.