VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 09: Heaps and top-k

Lesson 9.2 of 12 in this module Unrolled Pro

Last Stone Weight

Repeatedly smash the two heaviest stones and report what's left. From sorting the whole list every round (O(n² log n)), to keeping it sorted with binary insertion (O(n²) from shifting), to a max-heap built in O(n) with O(log n) per round (O(n log n)). Then the version where you choose the pairs, which becomes a subset-sum DP, and the ML twin: always combine the two lightest, which builds a Huffman code for token frequencies.

about 10 min 5 Python examples 2 quick checks

Problem. You have stones with positive integer weights. Each turn, take the two heaviest, x ≤ y, and smash them: if x == y both are destroyed, otherwise a stone of weight y − x remains. When at most one stone is left, return its weight (or 0).

text
[2, 7, 4, 1, 8, 1]
8 and 7 → 1     [2, 4, 1, 1, 1]
4 and 2 → 2     [2, 1, 1, 1]
2 and 1 → 1     [1, 1, 1]
1 and 1 → 0     [1]                  →   1

Every round asks the same question, "what are the two largest right now?", while the collection changes. That's a priority queue, and the cleanest first use of a heap.

ML context. The mirror process, always combine the two smallest, is how Huffman coding assigns short codes to frequent symbols: the basis of compressed token streams and a classic example of greedy merging with a heap (Change B). The same "repeatedly take the best pair" loop appears in agglomerative clustering, where the two closest clusters merge.


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Last Stone Weight"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee