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

Lesson 9.4 of 12 in this module Unrolled Pro

K Closest Points to Origin

The k points nearest the origin. From sorting all points by distance (O(n log n)), to a max-heap of size k keyed on squared distance with no square roots (O(n log k)), to quickselect on distance (O(n) average). Then a stream of points, the ML version: top-k most similar embeddings by cosine similarity, closest to an arbitrary query point, and when many queries justify building an index instead of scanning.

about 10 min 4 Python examples 2 quick checks

Problem. Given points, a list of (x, y), and k, return the k points closest to the origin (Euclidean distance), in any order.

text
points = [(1, 3), (-2, 2)],          k = 1   →   [(-2, 2)]       (√8 < √10)
points = [(3, 3), (5, -1), (-2, 4)], k = 2   →   [(3, 3), (-2, 4)]

It's lesson 9.3 with a key: rank items by a computed score instead of their value. The interesting decisions are which heap (max-heap of the k best, so the worst candidate is on top), and what to compute (squared distances, no square roots).

ML context. Replace "points" with embeddings and "distance to the origin" with distance to a query embedding, and this is the retrieval step of every RAG system, recommender and k-NN classifier: score every candidate against the query and keep the k best. Brute-force scanning with a heap is exactly what a "flat" vector index does, and it's the baseline every approximate index is measured against (Change B).


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 "K Closest Points to Origin"

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