r/DSALeetCode • • 4d ago

LeetCode: 1046. Last Stone Weight

Post image

Go's container/heap only builds min-heaps. You get a max-heap by lying to it. Define Less as greater-than, and that one inverted comparison is the whole difference.

Why sorting is the wrong shape for Last Stone Weight: sort, take the two heaviest, smash them, put the remainder back in the right place. That's an insertion, O(n) every round.

The deeper mismatch is that sorting answers a question nobody asked. This problem never needs the third-heaviest stone. It needs the maximum, repeatedly, from a collection that keeps changing.

A heap keeps exactly one promise: the largest is at the root. Read its backing array left to right, and it looks close to random, and that's the point. Maintaining less is what makes it cheaper.

Did inverting Less feel wrong the first time you did it?

Day 78/365 of my LeetCode challenge: 1046. Last Stone Weight. Problem link and full breakdown in today's newsletter.

https://www.linkedin.com/pulse/leetcode-1046-last-stone-weight-easy-archit-agarwal-ummqc

1 Upvotes

1 comment sorted by

1

u/nian2326076 4d ago

Using a max-heap is a more suitable approach for the Last Stone Weight problem since you need to consistently retrieve the largest stone. This can save time compared to sorting for every operation. For practicing your technical skills further, consider using PracHub to tackle more problems and refine your understanding of data structures.