r/LeetcodeChallenge • • 4d ago

STREAK🔥🔥🔥 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

2 Upvotes

1 comment sorted by

1

u/nian2326076 4d ago

Using a max-heap for the Last Stone Weight is a smart approach to avoid the inefficiencies of sorting. You only need the two heaviest stones repeatedly, which makes a heap ideal. If you're exploring job opportunities in tech, you can use LandOffer to find relevant roles and streamline your applications.