{"id":"k-closest-points-to-origin","title":"K Closest Points to Origin","difficulty":"medium","patterns":["heap"],"primaryConcept":"heap-top-k","concepts":["heap-top-k"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"stacks-queues","syntheticTestConfig":{"inputShape":"points-2d","primaryParam":"points","sizeMetric":"length","secondaryParams":{"k":{"strategy":"proportion","proportion":0.25}},"valueRange":{"min":-10000,"max":10000}},"executionStyle":"solution-method","compareMode":"unordered-array","description":"Given an array of points where `points[i] = [x_i, y_i]`, return the `k` points closest to the origin `(0, 0)`.\n\nThe distance between two points is the squared Euclidean distance `x_i^2 + y_i^2`. You may return the answer in any order.","examples":[{"input":"points = [[1,3],[-2,2]], k = 1","output":"[[-2,2]]","explanation":"[-2,2] has squared distance 8, while [1,3] has squared distance 10."},{"input":"points = [[3,3],[5,-1],[-2,4]], k = 2","output":"[[3,3],[-2,4]]","explanation":"The two smallest squared distances are 18 and 20."},{"input":"points = [[0,1],[1,0],[2,2]], k = 2","output":"[[0,1],[1,0]]","explanation":"Both unit-distance points are closer than [2,2]."}],"constraints":[{"id":"1-k-points-length-10-4","text":"1 <= k <= len(points) <= 10^4","check":[{"kind":"valueRange","target":"k","selector":"value","min":1,"max":{"sizeOfInput":"points","measure":"arrayLength"}},{"kind":"sizeRange","target":"points","measure":"arrayLength","max":10000}]},{"id":"10-4-x-i-y-i-10-4","text":"-10^4 <= x_i, y_i <= 10^4","check":[{"kind":"valueRange","target":"points","selector":"tupleItemsAtIndex","index":0,"min":-10000,"max":10000},{"kind":"valueRange","target":"points","selector":"tupleItemsAtIndex","index":1,"min":-10000,"max":10000}]},{"id":"the-selected-k-points-are-unique-for-the-provided-tests","text":"The selected k points are unique for the provided tests."}],"starterCode":"class Solution:\n    def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:\n        # Your code here\n        pass","functionName":"kClosest","testCases":[{"id":"1","input":{"points":[[1,3],[-2,2]],"k":1},"expected":[[-2,2]],"description":"Choose the closer of two points."},{"id":"2","input":{"points":[[3,3],[5,-1],[-2,4]],"k":2},"expected":[[3,3],[-2,4]],"description":"Keep the two smallest distances."},{"id":"3","input":{"points":[[0,1],[1,0],[2,2]],"k":2},"expected":[[0,1],[1,0]],"description":"Both unit-distance points are selected."},{"id":"4","input":{"points":[[2,0],[1,1],[-1,-1],[3,3]],"k":3},"expected":[[1,1],[-1,-1],[2,0]],"description":"Discard the farthest point."},{"id":"5","input":{"points":[[0,0]],"k":1},"expected":[[0,0]],"description":"Single point."},{"id":"hidden-1","input":{"points":[[-5,4],[2,-1],[3,3],[1,2]],"k":2},"expected":[[2,-1],[1,2]],"description":"Two tied closest points are both selected."},{"id":"hidden-2","input":{"points":[[10,10],[-1,2],[4,0],[0,-3],[-2,-2]],"k":3},"expected":[[-1,2],[-2,-2],[0,-3]],"description":"Select three closest among mixed quadrants."},{"id":"hidden-3","input":{"points":[[7,7],[6,6],[5,5],[4,4]],"k":1},"expected":[[4,4]],"description":"Closest point appears at the end."},{"id":"h4","input":{"points":[[5,5],[1,1],[-2,1],[0,4]],"k":2},"expected":[[1,1],[-2,1]]},{"id":"h5","input":{"points":[[0,0],[2,2],[-1,-1],[3,1]],"k":3},"expected":[[0,0],[-1,-1],[2,2]]},{"id":"topup-1","input":{"points":[[6,8],[1,-2],[-3,4],[2,2],[0,5]],"k":2},"expected":[[1,-2],[2,2]],"description":"Top-up case 1: select two uniquely closest points from mixed quadrants."},{"id":"topup-2","input":{"points":[[9,0],[-4,-3],[0,-2],[3,1],[5,5],[-1,1]],"k":4},"expected":[[-1,1],[0,-2],[3,1],[-4,-3]],"description":"Top-up case 2: keep the four closest points while preserving clear distance ordering."}],"hints":[{"level":1,"content":"Compare points by squared distance so you do not need square roots."},{"level":2,"content":"Keep only k candidates as you scan; the farthest retained point should be easiest to remove.","revealPattern":true},{"level":3,"content":"Use a max-heap of size k, push each point with its distance, and pop when the heap grows beyond k."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Choose how much heap state to keep while scanning the points.","approaches":[{"id":"bounded-max-heap","name":"Bounded max-heap","summary":"Scan points once, push each distance, and remove the farthest retained point whenever size exceeds k.","decisionReason":"The heap size stays k, so each update costs log k instead of ordering all n points.","complexity":{"time":"O(n log k)","space":"O(k)"},"tradeoffs":["Best when k is much smaller than n.","Requires representing the farthest retained point at the top."],"isOptimal":true,"steps":["Compute squared distance.","Push point into the heap.","If heap size exceeds k, remove the farthest retained point."]},{"id":"full-min-heap","name":"Full min-heap","summary":"Push every point into a min-heap by distance, then pop k closest points at the end.","decisionReason":"This still uses the heap pattern, but it keeps all n points when only k retained candidates are needed.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Simpler heap orientation, but stores and orders points that will never be returned."],"isOptimal":false}]},"codingCheckpoints":[{"id":"init-heap","title":"Initialize retained-point heap","description":"Create the empty priority structure before scanning points.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"initializes_heap_storage","scope":"init-heap","readMode":"heap-value-query-v1"}]},"commonMistakes":["Starting with a prefilled heap","Rebuilding the heap from scratch for every point"],"hint":"Start with one empty heap that will hold at most k points.","semanticSpec":{"intent":"Create the empty heap that will hold retained closest-point candidates.","doneWhen":"The heap container exists and starts empty before the scan.","shouldFailWhen":"The heap starts prefilled or is created only after processing points.","roles":["heap container","empty initial state","retained candidates"],"mustProve":["An empty heap container is initialized.","The heap is available before the point scan."],"mustNotAccept":["A prefilled heap.","A non-priority result list used as the retained structure."],"equivalentVariants":["Use an empty list with heap operations.","Use an empty priority queue object."],"proofSnippets":[{"id":"py-k-closest-init-heap","language":"python","code":"def kClosest(points, k):\n    heap = []"}]}},{"id":"loop-through-points","title":"Scan every point","description":"Iterate through all points so each one can compete for the retained set.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"scans_input_values","scope":"scan-points","readMode":"heap-value-query-v1"}]},"commonMistakes":["Only checking the first k points","Skipping points after the heap first reaches size k"],"hint":"Every point needs one chance to enter the heap.","semanticSpec":{"intent":"Scan the input points so every candidate can be evaluated.","doneWhen":"There is a loop over the point sequence.","shouldFailWhen":"The scan does not traverse the input sequence.","roles":["input scan","current point","candidate evaluation"],"mustProve":["The point sequence is iterated.","Each current point is available to later heap logic."],"mustNotAccept":["Processing only a prefix.","Using a loop unrelated to the input points."],"equivalentVariants":["Loop directly over points.","Loop over point indices and read the current point."],"proofSnippets":[{"id":"py-k-closest-scan-points","language":"python","code":"def kClosest(points, k):\n    heap = []\n    for point in points:\n        current_size = len(heap)"}]}},{"id":"heap-push","title":"Push each point by distance","description":"Compute squared distance and push the current point together with its distance-derived priority.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"pushes_heap_values","scope":"point-distance-push","readMode":"heap-value-query-v1"}]},"commonMistakes":["Using square root instead of squared distance","Pushing only the distance and losing the point coordinates"],"hint":"Store both priority and coordinates so you can return the selected points.","semanticSpec":{"intent":"Insert each current point into the heap with distance-derived priority.","doneWhen":"The current point contributes a heap entry during the scan.","shouldFailWhen":"The code scans points but never inserts a heap entry.","roles":["current point","distance priority","heap insert"],"mustProve":["The priority is derived from x*x + y*y for the current point.","The heap insertion occurs during the point scan.","The inserted heap entry preserves enough point coordinate data to return the selected points later."],"mustNotAccept":["Pushing a constant entry.","Pushing only a distance without retaining point coordinates.","Using a priority unrelated to squared distance."],"equivalentVariants":["Use negative squared distance in a min-heap to simulate a max-heap.","Use a native max-priority queue keyed by squared distance."],"proofSnippets":[{"id":"py-k-closest-push-points","language":"python","code":"import heapq\n\n\ndef kClosest(points, k):\n    heap = []\n    for point in points:\n        x = point[0]\n        y = point[1]\n        dist = x * x + y * y\n        heapq.heappush(heap, [-dist, x, y])"}]}},{"id":"heap-size-check","title":"Evict the farthest retained point","description":"Keep the heap ordered so overflow removal discards the farthest retained candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"maintains_heap_size_bound","scope":"bounded-point-overflow","readMode":"heap-value-query-v1"}]},"commonMistakes":["Popping when the heap size is equal to k","Letting the heap grow beyond k for the rest of the scan","Removing the closest point instead of the farthest retained point"],"hint":"After every push, pop once only when the heap has more than k entries, and make that pop remove the farthest retained candidate.","semanticSpec":{"intent":"Maintain a bounded heap of at most k retained point candidates while ensuring each overflow removes the current farthest retained point.","doneWhen":"Every overflow beyond k triggers a heap pop from a farthest-first retained ordering.","shouldFailWhen":"The heap is allowed to remain larger than k, the size guard uses the wrong bound, or the overflow pop removes a closer retained point.","roles":["heap","size bound k","overflow removal","farthest retained candidate"],"mustProve":["The heap size is compared with k.","A heap pop removes one overflow entry.","The popped overflow entry is the farthest retained candidate under the distance priority."],"mustNotAccept":["Using >= k and dropping too many candidates.","Checking k without popping from the heap.","Popping the closest point instead of the farthest retained point."],"equivalentVariants":["Use negative squared distances in a min-heap so the heap root represents the farthest retained point.","Use a native max-priority queue keyed by squared distance and pop when its size exceeds k.","Use an equivalent strict overflow check that removes the current worst retained candidate."],"proofSnippets":[{"id":"py-k-closest-bound-heap","language":"python","code":"import heapq\n\n\ndef kClosest(points, k):\n    heap = []\n    for point in points:\n        x = point[0]\n        y = point[1]\n        dist = x * x + y * y\n        heapq.heappush(heap, [-dist, x, y])\n        if len(heap) > k:\n            heapq.heappop(heap)"}]}},{"id":"return-points","title":"Return retained points","description":"Return the point coordinates that remain in the bounded heap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"returns_heap_result","scope":"return-values","readMode":"heap-value-query-v1"}]},"commonMistakes":["Returning the heap size instead of the retained points","Returning a constant or unrelated list","Dropping the heap result before returning"],"hint":"Project the surviving heap entries back to point coordinates.","semanticSpec":{"intent":"Return the selected points from the bounded heap.","doneWhen":"The function returns a value derived from the retained heap entries.","shouldFailWhen":"The code maintains the heap but returns an unrelated value or never returns the retained points.","roles":["bounded heap","retained entries","returned points"],"mustProve":["The returned value is derived from the heap that stores retained point entries."],"mustNotAccept":["Returning a constant.","Returning an unrelated local collection.","Omitting the final return."],"equivalentVariants":["Use a list comprehension over the heap entries.","Build a result list from the surviving heap entries and return it."],"proofSnippets":[{"id":"py-k-closest-return-points","language":"python","code":"import heapq\n\n\ndef kClosest(points, k):\n    heap = []\n    for point in points:\n        x = point[0]\n        y = point[1]\n        dist = x * x + y * y\n        heapq.heappush(heap, [-dist, x, y])\n        if len(heap) > k:\n            heapq.heappop(heap)\n    return [[entry[1], entry[2]] for entry in heap]"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"The points","eyebrow":"Read the problem","title":"The k closest to the origin","workspacePanel":"problem","body":["You are given a list of points on a plane and a number k. Return the k points nearest to the origin (0, 0). Order does not matter, and distance is measured as x*x + y*y, so no square roots are needed.","Nothing in the task asks for the points in order, only for which k they are. That gap between what is asked and what a ranking gives you is where the work can be cut."]},{"id":"sort-baseline","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Measure every point, sort the distances, take exactly k","summary":"It returns exactly k points even when distances tie at the cutoff, but it pays to rank every point first, including the ones it will never return.","workspacePanel":"trace","body":["Compute every squared distance, sort them to find the k-th smallest as the cutoff, then take points within the cutoff but stop the moment k have been collected so ties never spill past k."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"dists = []\nfor point in points:\n    x = point[0]\n    y = point[1]\n    dists.append(x * x + y * y)\norder = sorted(dists)\ncutoff = order[k - 1]\nresult = []\ntaken = 0\nfor i in range(len(points)):\n    if dists[i] < cutoff and taken < k:\n        result.append(points[i])\n        taken = taken + 1\nfor i in range(len(points)):\n    if dists[i] == cutoff and taken < k:\n        result.append(points[i])\n        taken = taken + 1\nreturn result","steps":[{"id":"measure","title":"Measure each point into a distance list","codeLine":5,"summary":"Walking [[3,3],[1,1],[-2,1],[0,4],[0,1]] front to back records distances 18, 2, 5, 16, 1.","state":{"nums":[18,2,5,16,1],"i":0,"labels":{"nums":"dists"}}},{"id":"measured","title":"Every point now carries its squared distance","codeLine":5,"summary":"All five distances are recorded: 18, 2, 5, 16, 1. Nothing has been ordered yet.","state":{"nums":[18,2,5,16,1],"i":4,"labels":{"nums":"dists"}}},{"id":"sorted","title":"Sort to find the k-th smallest distance","codeLine":6,"summary":"The sort orders all five distances to 1, 2, 5, 16, 18, so the k-th smallest, distance 2, is the cutoff.","state":{"nums":[1,2,5,16,18],"i":1,"labels":{"nums":"dists"}}},{"id":"selected","title":"Collect points up to exactly k","codeLine":12,"summary":"Distance 1 is below the cutoff and distance 2 is at it, giving points [0,1] and [1,1]; collection stops at k = 2, so a tie at the cutoff could never push past two.","state":{"nums":[1,2,5,16,18],"i":1,"labels":{"nums":"dists"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const dists = [];\nfor (const point of points) {\n    const x = point[0];\n    const y = point[1];\n    dists.push(((x * x) + (y * y)));\n}\nconst order = [...dists].sort((a, b) => a - b);\nconst cutoff = order[(k - 1)];\nconst result = [];\nlet taken = 0;\nfor (let i = 0; i < points.length; i++) {\n    if (dists[i] < cutoff && taken < k) {\n        result.push(points[i]);\n        taken = taken + 1;\n    }\n}\nfor (let i = 0; i < points.length; i++) {\n    if (dists[i] === cutoff && taken < k) {\n        result.push(points[i]);\n        taken = taken + 1;\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":17,"15":18,"16":19,"17":20,"18":23},"statementBundles":{"5":{"startLine":5,"endLine":6},"13":{"startLine":14,"endLine":16},"17":{"startLine":20,"endLine":22}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const dists: Array<number> = [];\nfor (const point of points) {\n    const x = point[0];\n    const y = point[1];\n    dists.push(((x * x) + (y * y)));\n}\nconst order = [...dists].sort((a, b) => a - b);\nconst cutoff = order[(k - 1)];\nconst result: Array<Array<number>> = [];\nlet taken = 0;\nfor (let i = 0; i < points.length; i++) {\n    if (dists[i] < cutoff && taken < k) {\n        result.push(points[i]);\n        taken = taken + 1;\n    }\n}\nfor (let i = 0; i < points.length; i++) {\n    if (dists[i] === cutoff && taken < k) {\n        result.push(points[i]);\n        taken = taken + 1;\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":17,"15":18,"16":19,"17":20,"18":23},"statementBundles":{"5":{"startLine":5,"endLine":6},"13":{"startLine":14,"endLine":16},"17":{"startLine":20,"endLine":22}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> dists = new ArrayList<>();\nfor (List<Integer> point : points) {\n    int x = point.get(0);\n    int y = point.get(1);\n    dists.add(((x * x) + (y * y)));\n}\nList<Integer> order = new ArrayList<>(dists);\nCollections.sort(order);\nint cutoff = order.get(k - 1);\nList<List<Integer>> result = new ArrayList<>();\nint taken = 0;\nfor (int i = 0; i < points.size(); i++) {\n    if ((dists.get(i) < cutoff && taken < k)) {\n        result.add(points.get(i));\n        taken = taken + 1;\n    }\n}\nfor (int i = 0; i < points.size(); i++) {\n    if ((dists.get(i) == cutoff && taken < k)) {\n        result.add(points.get(i));\n        taken = taken + 1;\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":9,"8":10,"9":11,"10":12,"11":13,"12":14,"13":15,"14":18,"15":19,"16":20,"17":21,"18":24},"statementBundles":{"5":{"startLine":5,"endLine":6},"6":{"startLine":7,"endLine":8},"13":{"startLine":15,"endLine":17},"17":{"startLine":21,"endLine":23}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> dists = new();\nforeach (var point in points) {\n    int x = point[0];\n    int y = point[1];\n    dists.Add(x * x + y * y);\n}\nList<int> order = dists.OrderBy(value => value).ToList();\nint cutoff = order[k - 1];\nList<List<int>> result = new();\nint taken = 0;\nfor (int i = 0; i < points.Count; i++) {\n    if (dists[i] < cutoff && taken < k) {\n        result.Add(points[i]);\n        taken = taken + 1;\n    }\n}\nfor (int i = 0; i < points.Count; i++) {\n    if (dists[i] == cutoff && taken < k) {\n        result.Add(points[i]);\n        taken = taken + 1;\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":17,"15":18,"16":19,"17":20,"18":23},"statementBundles":{"5":{"startLine":5,"endLine":6},"13":{"startLine":14,"endLine":16},"17":{"startLine":20,"endLine":22}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> dists;\nfor (vector<int> point : points) {\n    int x = point[0];\n    int y = point[1];\n    dists.push_back(((x * x) + (y * y)));\n}\nvector<int> order = sortedVector(dists);\nint cutoff = order[(k - 1)];\nvector<vector<int>> result;\nint taken = 0;\nfor (int i = 0; i < points.size(); i++) {\n    if ((dists[i] < cutoff && taken < k)) {\n        result.push_back(points[i]);\n        taken = taken + 1;\n    }\n}\nfor (int i = 0; i < points.size(); i++) {\n    if ((dists[i] == cutoff && taken < k)) {\n        result.push_back(points[i]);\n        taken = taken + 1;\n    }\n}\nreturn result;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":14,"14":17,"15":18,"16":19,"17":20,"18":23},"statementBundles":{"5":{"startLine":5,"endLine":6},"13":{"startLine":14,"endLine":16},"17":{"startLine":20,"endLine":22}}}}}},{"id":"sort-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Name the cost","title":"With n points and k = 1, how much of the sort is wasted?","workspacePanel":"visualizer","summary":"The sort left distances 1, 2, 5, 16, 18 in order, but with k = 1 the answer reads only the first slot.","options":[{"id":"orders-all","label":"Nearly all of it: every point is ordered against every other to surface one answer","rationale":"Sorting puts all n distances in full order at O(n log n) cost, but for k = 1 only the smallest is needed, so the relative order of the other n-1 is thrown away.","isCorrect":true},{"id":"none-wasted","label":"None: the sort stops once the first point is placed","rationale":"A full sort does not stop early; it orders the entire list before the slice can read position 0, so the n-1 points past the answer are still ranked."},{"id":"half-wasted","label":"About half, since sorting only compares each point once","rationale":"Sorting is O(n log n), not one comparison per point, and for k = 1 every point past the nearest is ordered needlessly, which is nearly the whole list rather than half."}],"answer":"Nearly all of it. The sort ranks all n distances at O(n log n), but k = 1 needs only the smallest, so ordering the other points is wasted work that grows with the whole input.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sort-cost-state","state":{"nums":[1,2,5,16,18],"current":0,"labels":{"nums":"dists","current":"first"}}}]}},{"id":"full-sort-bridge","chapter":"The trick","kind":"info","eyebrow":"Spend less","title":"The full sort pays for order it never reads","workspacePanel":"visualizer","body":["Sorting put all five distances 1, 2, 5, 16, 18 in order at O(n log n) cost, but the answer only ever reads the front. Ordering 16 against 18 did nothing the result could use.","So drop the full ranking and make one pass instead. The only question left is how much of the input a single scan has to hold on to before it can name the answer."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"full-sort-state","state":{"nums":[1,2,5,16,18],"labels":{"nums":"dist"}}}]}},{"id":"bounded-set","kind":"case-probe","chapter":"The trick","eyebrow":"Find the state","title":"To answer without ranking everything, how many points must you carry as you scan?","workspacePanel":"visualizer","summary":"You make a single pass over [[3,3],[1,1],[-2,1],[0,4],[0,1]], holding on to as little as the answer allows.","options":[{"id":"k-points","label":"Exactly k: the current best candidates, refreshed as closer points arrive","rationale":"The answer is k points, so k retained candidates are enough; a point closer than the worst kept one replaces it, and everything farther can be dropped on sight without ranking it.","isCorrect":true},{"id":"all-points","label":"All n, because any earlier point might still belong in the answer","rationale":"A point only belongs in the answer if it is closer than the current k-th best, so once k candidates exist, a farther point can be rejected immediately without keeping it around."},{"id":"one-point","label":"Just one: the single closest seen so far","rationale":"One point answers k = 1, but for general k the set must hold k candidates at once, since the k-th closest can only be known by retaining that many."}],"answer":"Exactly k. Carry the k best candidates as you scan; a closer point bumps the current worst, and a farther point is dropped on the spot, so the other points are never ranked.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bounded-state","state":{"nums":[18,2,5,16,1],"current":2,"labels":{"nums":"dist"}}}]}},{"id":"evict-worst","kind":"case-probe","chapter":"The trick","eyebrow":"Find the rule","title":"The set already holds k points and a new one arrives. Which point should be the easy one to drop?","workspacePanel":"visualizer","summary":"The set holds distances 18 and 2; a third point appears and only k may stay.","options":[{"id":"current-farthest","label":"The farthest one currently kept, compared against the newcomer","rationale":"Only the current worst can be displaced: if the newcomer is closer than the farthest kept point, it takes that slot; if not, the newcomer itself is the one to drop. Either way the deciding comparison is against the farthest.","isCorrect":true},{"id":"closest","label":"The closest one kept, since the newer points deserve a chance","rationale":"The closest kept point is guaranteed to belong in any answer, so dropping it could discard a true closest point and let a farther one survive."},{"id":"oldest","label":"Whichever was added earliest, to keep the set fresh","rationale":"Arrival order has nothing to do with distance; a point added early can still be one of the k closest, so age is the wrong thing to compare."}],"answer":"The farthest currently kept. Each new point is weighed against the current worst, so the structure must surface that farthest point instantly, which a max-heap keyed by distance does at its root.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"evict-state","state":{"heap":{"values":[18,2],"current":0,"name":"kept points (by distance)"}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The trick","eyebrow":"Pick the route","title":"How much heap state should the scan keep?","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Choose how much heap state to keep while scanning the points.","approaches":[{"id":"bounded-max-heap","name":"Bounded max-heap","summary":"Maintain only k candidate points and make the farthest current candidate the easiest one to replace.","decisionReason":"The retained state is limited to k candidates, so the scan avoids ordering points that cannot affect the answer.","complexity":{"time":"O(n log k)","space":"O(k)"},"tradeoffs":["Best when k is much smaller than n.","Requires representing the farthest retained point at the top."],"isOptimal":true,"steps":["It holds only k candidate points along with their squared distances.","It fits because the answer order is irrelevant, so only membership in the closest set matters.","It wins when k is smaller than n, since each new point is weighed against just the current worst candidate."]},{"id":"full-min-heap","name":"Full min-heap","summary":"Push every point into a min-heap by distance, then pop k closest points at the end.","decisionReason":"This still uses the heap pattern, but it keeps all n points when only k retained candidates are needed.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["The heap orientation is simpler, but it stores and orders points that will never be returned."],"isOptimal":false}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"heap":{"values":[18,2],"current":0,"highlighted":[1],"name":"kept points (by distance)"}}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"The farthest sits at the root","workspacePanel":"visualizer","body":["Keep the kept distances in a max-heap, so the farthest retained point always rises to the root. Every point gets its chance to enter, and the root is the one candidate a closer arrival can knock out.","The run below uses [[3,3],[1,1],[-2,1],[0,4],[0,1]] with k = 2. Each step turns on one question: does the new point beat the current worst?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"heap":{"values":[18,5,2],"current":0,"name":"kept points (by distance)"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Run the heap","title":"Keep the two closest of five points","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fill-two","state":{"heap":{"values":[18,2],"current":0,"name":"kept points (by distance)"}}},{"id":"overflow-near","state":{"heap":{"values":[18,2,5],"current":0,"name":"kept points (by distance)"}}},{"id":"overflow-far","state":{"heap":{"values":[16,5,2],"current":0,"name":"kept points (by distance)"}}},{"id":"final-swap","state":{"heap":{"values":[5,2,1],"current":0,"name":"kept points (by distance)"}}}]},"beats":[{"id":"fill-two","title":"The first two points fill the heap. Does anything get dropped yet?","summary":"[3,3] at distance 18 and [1,1] at distance 2 are kept; k is 2.","prompt":"The heap now holds distances 18 and 2.","options":[{"id":"no-drop","label":"No: the heap is exactly k, which is allowed","rationale":"A heap of size k is full but not over: trimming happens only when a push makes the size exceed k, so both points stay.","isCorrect":true},{"id":"drop-18","label":"Yes: distance 18 leaves because it is the farthest","rationale":"The farthest is only dropped when the heap grows past k. At exactly k, nothing has overflowed, so 18 stays for now.","isCorrect":false},{"id":"drop-2","label":"Yes: distance 2 leaves to make room for later points","rationale":"The closest kept point is never the one dropped, and no overflow has happened yet, so nothing leaves.","isCorrect":false}],"answer":"Nothing drops. The heap is exactly k, which is allowed; the root distance 18 is just waiting at the top in case a closer point forces an overflow."},{"id":"overflow-near","title":"Point [-2,1] at distance 5 is pushed, making the heap size 3. Which distance leaves?","summary":"The heap held 18 and 2; pushing 5 overflows past k = 2.","prompt":"After the push the heap holds 18, 2, and 5.","options":[{"id":"pop-18","label":"18 leaves: it is the farthest of the three","rationale":"The root is the largest distance, 18, so the overflow pop removes it, leaving the two closer points 5 and 2.","isCorrect":true},{"id":"pop-5","label":"5 leaves: it was the most recent to arrive","rationale":"The pop removes the farthest entry; 5 is closer than 18, so 5 is kept and 18 goes.","isCorrect":false},{"id":"pop-2","label":"2 leaves: the heap keeps the larger distances","rationale":"A max-heap pops its root, which is the largest distance, so the closest point at distance 2 is exactly the one that stays.","isCorrect":false}],"answer":"18 leaves. The newcomer at distance 5 is closer than the kept farthest, so 18 is popped from the root and the heap settles to 5 and 2."},{"id":"overflow-far","title":"Point [0,4] at distance 16 is pushed next. Which distance leaves this time?","summary":"The heap held 5 and 2; pushing 16 overflows again.","prompt":"After the push the heap holds 16, 5, and 2.","options":[{"id":"pop-16","label":"16 leaves: the point that was just pushed is itself the farthest","rationale":"16 is larger than both kept distances, so it rises to the root and the very next pop removes it, leaving 5 and 2 unchanged.","isCorrect":true},{"id":"pop-5","label":"5 leaves: the heap always drops a previously kept point","rationale":"The pop targets the farthest, and 16 is farther than 5, so the newcomer is discarded and 5 survives.","isCorrect":false},{"id":"pop-2","label":"2 leaves: the closest is rotated out to balance the heap","rationale":"The closest point is never evicted; the max-heap pops its largest, which here is the freshly pushed 16.","isCorrect":false}],"answer":"16 leaves. A pushed point that is farther than everything kept becomes the root and is immediately popped, so the bounded set stays at 5 and 2."},{"id":"final-swap","title":"The last point [0,1] at distance 1 is pushed. After the overflow, which two distances remain?","summary":"The heap held 5 and 2; pushing 1 overflows one final time.","prompt":"After the push the heap holds 5, 2, and 1.","options":[{"id":"keep-2-1","label":"Distances 2 and 1, the two nearest points","rationale":"5 is the farthest of the three, so it pops from the root, leaving the two closest distances 2 and 1, which are points [1,1] and [0,1].","isCorrect":true},{"id":"keep-5-1","label":"Distances 5 and 1","rationale":"5 is the farthest kept distance once 1 arrives, so it is the one popped, not retained alongside 1.","isCorrect":false},{"id":"keep-5-2","label":"Distances 5 and 2, since 1 is too small to matter","rationale":"A smaller distance means a closer point, which is exactly what the answer wants, so 1 stays and the farther 5 is dropped.","isCorrect":false}],"answer":"Distances 2 and 1 remain. The new closest point at distance 1 forces out the farthest kept distance 5, and the surviving points [1,1] and [0,1] are the answer."}]},{"id":"pop-at-equal-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Could a plain min-heap by distance work the same way?","summary":"Push each distance into an ordinary min-heap and, on overflow, pop the root to stay at size k. Every push and pop is a real heap operation, and the size never passes k, so the bound looks right. The root of a min-heap is the closest point, so overflow throws away the answer.","pitfall":"The heap below is a min-heap keyed by raw distance, so its root is the smallest distance, and popping that root on overflow removes the closest point instead of the farthest.","whyItMatters":"A min-heap surfaces its smallest value at the root, so the overflow pop ejects the nearest point and lets the farther ones survive. On [[3,3],[1,1],[-2,1]] with k = 2, the third push overflows and pops distance 2, the closest point [1,1], leaving distances 5 and 18, the two farthest. To make the root the farthest retained point, store negated distances in the min-heap (or use a max-heap), so popping the root sheds the point that is farthest from the origin.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"import heapq\nheap: list[tuple[int, int, int]] = []\nfor point in points:\n    x = point[0]\n    y = point[1]\n    dist = x * x + y * y\n    heapq.heappush(heap, (dist, x, y))\n    if len(heap) > k:\n        heapq.heappop(heap)\nresult = []\nwhile heap:\n    entry = heapq.heappop(heap)\n    result.append([entry[1], entry[2]])\nreturn result","steps":[{"id":"push-two","title":"points = [[3,3],[1,1],[-2,1]], k = 2: distances 18 and 2 are in the min-heap","codeLine":7,"summary":"After pushing 18 and 2, the min-heap settles the smallest distance, 2, at the root, with 18 below it.","state":{"heap":{"values":[2,18],"current":0,"name":"kept points (by distance)"}}},{"id":"push-overflow","title":"Push distance 5: the heap reaches size 3 and overflows k","codeLine":7,"summary":"Pushing 5 makes the heap {2, 18, 5}; the min-heap keeps the smallest, 2, at the root, and size 3 now exceeds k.","state":{"heap":{"values":[2,18,5],"current":0,"name":"kept points (by distance)"}}},{"id":"pop-closest","title":"The overflow pop removes the root, which is the smallest distance","codeLine":9,"summary":"Popping the root sheds distance 2, the closest point [1,1], and the heap reorders to {5, 18}.","state":{"heap":{"values":[5,18],"current":0,"visited":[1],"name":"kept points (by distance)"}}},{"id":"wrong-result","title":"The scan returns distances 5 and 18, the two farthest","codeLine":14,"summary":"The nearest point was the one ejected, so the heap returns [-2,1] and [3,3], the two farthest points instead of the two closest.","state":{"heap":{"values":[5,18],"current":0,"name":"kept points (by distance)"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const heap = new Heap(compareHeapValues);\nfor (const point of points) {\n    const x = point[0];\n    const y = point[1];\n    const dist = (x * x) + (y * y);\n    heap.push([dist, x, y]);\n    if (heap.size() > k) {\n        heap.pop();\n    }\n}\nconst result = [];\nwhile (heap.size() > 0) {\n    const entry = heap.pop();\n    result.push([entry[1], entry[2]]);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":13,"13":14,"14":16},"statementBundles":{"9":{"startLine":8,"endLine":10},"13":{"startLine":14,"endLine":15}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const heap: Heap<[number, number, number]> = new Heap<[number, number, number]>(compareHeapValues);\nfor (const point of points) {\n    const x = point[0];\n    const y = point[1];\n    const dist = (x * x) + (y * y);\n    heap.push([dist, x, y]);\n    if (heap.size() > k) {\n        heap.pop();\n    }\n}\nconst result: Array<Array<number>> = [];\nwhile (heap.size() > 0) {\n    const entry = heap.pop()!;\n    result.push([entry[1], entry[2]]);\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":13,"13":14,"14":16},"statementBundles":{"9":{"startLine":8,"endLine":10},"13":{"startLine":14,"endLine":15}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"PriorityQueue<List<Integer>> heap = new PriorityQueue<>((left, right) -> {\n    int commonLength = Math.min(left.size(), right.size());\n    for (int index = 0; index < commonLength; index++) {\n        int order = Integer.compare(left.get(index), right.get(index));\n        if (order != 0) return order;\n    }\n    return Integer.compare(left.size(), right.size());\n});\nfor (List<Integer> point : points) {\n    int x = point.get(0);\n    int y = point.get(1);\n    int dist = (x * x) + (y * y);\n    heap.offer(new ArrayList<>(List.of(dist, x, y)));\n    if (heap.size() > k) {\n        heap.poll();\n    }\n}\nList<List<Integer>> result = new ArrayList<>();\nwhile (!heap.isEmpty()) {\n    List<Integer> entry = heap.poll();\n    result.add(new ArrayList<>(List.of(entry.get(1), entry.get(2))));\n}\nreturn result;","lineMap":{"2":1,"3":9,"4":10,"5":11,"6":12,"7":13,"8":14,"9":15,"10":18,"11":19,"12":20,"13":21,"14":23},"statementBundles":{"2":{"startLine":1,"endLine":8},"9":{"startLine":15,"endLine":17},"13":{"startLine":21,"endLine":22}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"PriorityQueue<(int, int, int), (int, int, int)> heap = new();\nforeach (var point in points) {\n    int x = point[0];\n    int y = point[1];\n    int dist = x * x + y * y;\n    (int, int, int) heapEntry = (dist, x, y);\n    heap.Enqueue(heapEntry, heapEntry);\n    if (heap.Count > k) {\n        heap.Dequeue();\n    }\n}\nList<List<int>> result = new();\nwhile (heap.Count > 0) {\n    (int, int, int) entry = heap.Dequeue();\n    result.Add(new List<int> { entry.Item2, entry.Item3 });\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":8,"9":9,"10":12,"11":13,"12":14,"13":15,"14":17},"statementBundles":{"7":{"startLine":6,"endLine":7},"9":{"startLine":9,"endLine":11},"13":{"startLine":15,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<tuple<int, int, int>> heap;\nfor (vector<int> point : points) {\n    int x = point[0];\n    int y = point[1];\n    int dist = (x * x) + (y * y);\n    heap.push_back(tuple<int, int, int>{dist, x, y}); push_heap(heap.begin(), heap.end(), greater<>());\n    if (heap.size() > k) {\n        heapPopValue(heap);\n    }\n}\nvector<vector<int>> result;\nwhile (!heap.empty()) {\n    tuple<int, int, int> entry = heapPopValue(heap);\n    result.push_back(vector<int>{get<1>(entry), get<2>(entry)});\n}\nreturn result;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":11,"11":12,"12":13,"13":14,"14":16},"statementBundles":{"9":{"startLine":8,"endLine":10},"13":{"startLine":14,"endLine":15}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["The push-then-trim rule held on a spread of distinct distances. A bounded-heap routine is easiest to break where the trim has to make a delicate call, or where order works against it.","Two are worth a look before coding: more points tied at the closest distance than there are slots, and a list whose nearest point arrives last, after the heap is already full."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"heap":{"values":[18,2],"current":0,"name":"kept points (by distance)"}}}]}},{"id":"tied-distances-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"Three points tie at the closest distance but k = 2. How many come back?","workspacePanel":"visualizer","summary":"points = [[1,1],[-1,-1],[1,-1]] all sit at squared distance 2, k = 2, and the third push has just overflowed the heap to size 3.","options":[{"id":"exactly-k","label":"Exactly two: the heap keeps k entries even when their distances are equal","rationale":"The third tied push makes the heap size 3, the strict overflow fires once, and a distance-2 entry is popped, so two distinct points remain. Equal distances do not collapse into one slot.","isCorrect":true},{"id":"all-three","label":"All three, because tied points are equally close so none can be dropped","rationale":"The answer is exactly k points, not every point at the minimum distance; when more than k tie, the overflow still trims down to k of them."},{"id":"just-one","label":"One, since identical distances are treated as the same candidate","rationale":"The heap stores one entry per point, not per distinct distance; tied distances stay as separate entries, so two survive rather than collapsing to one."}],"answer":"Two points come back. Each tied point is its own heap entry, so the third push overflows and one distance-2 entry is popped, leaving k = 2 points.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"tied-distances-state","state":{"heap":{"values":[2,2,2],"current":2,"visited":[0,1],"name":"third tied push overflows; the two settled entries stay"}}}]}},{"id":"closest-last-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"The nearest point arrives last, after the heap is already full. Does it still get in?","workspacePanel":"visualizer","summary":"For k = 1 the heap holds distance 50 when a final point at distance 2 appears.","options":[{"id":"yes-swaps","label":"Yes: it is pushed, becomes size 2, and the farther kept point is popped","rationale":"Every point is pushed regardless of arrival order; the new point at distance 2 overflows the heap, and the pop removes the farther distance 50, so the nearest wins.","isCorrect":true},{"id":"no-full","label":"No: once the heap is full it stops accepting new points","rationale":"The scan pushes every point and trims afterward; a full heap is never a reason to skip a point, or a late nearest point would be missed."},{"id":"no-order","label":"No: only points seen before the heap filled can be kept","rationale":"Arrival order does not protect kept points; a closer point always displaces the farthest, so a nearest point arriving last still takes its slot."}],"answer":"Yes. Each point is pushed first and trimmed second, so the late point at distance 2 overflows the heap and pops the farther distance 50, leaving the true nearest.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"closest-last-state","state":{"heap":{"values":[50],"current":0,"name":"kept points (by distance)"}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Build the bounded heap","workspacePanel":"visualizer","summary":"Scan the points once, hold at most k in a heap, and keep the farthest at the top.","body":["You have the rule and the trap that guards it: keep the k nearest seen so far in a heap whose top is the current farthest, and trade that farthest away only when a push actually overflows the bound.","Scan every point once, push each with a distance-based priority, trim back to k on a strict overflow, then read the surviving points out as the answer."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"heap":{"values":[18,2],"current":0,"name":"kept points (by distance)"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the bounded max-heap","summary":"Build the bounded max-heap scan one move at a time.","workspacePanel":"code","checkpoints":[{"id":"init-heap","title":"Initialize retained-point heap","description":"Create the empty priority structure before scanning points.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"initializes_heap_storage","scope":"init-heap","readMode":"heap-value-query-v1"}]},"commonMistakes":["Starting with a prefilled heap","Rebuilding the heap from scratch for every point"],"hint":"Start with one empty heap that will hold at most k points.","semanticSpec":{"intent":"Create the empty heap that will hold retained closest-point candidates.","doneWhen":"The heap container exists and starts empty before the scan.","shouldFailWhen":"The heap starts prefilled or is created only after processing points.","roles":["heap container","empty initial state","retained candidates"],"mustProve":["An empty heap container is initialized.","The heap is available before the point scan."],"mustNotAccept":["A prefilled heap.","A non-priority result list used as the retained structure."],"equivalentVariants":["Use an empty list with heap operations.","Use an empty priority queue object."],"proofSnippets":[{"id":"py-k-closest-init-heap","language":"python","code":"def kClosest(points, k):\n    heap = []"}]}},{"id":"loop-through-points","title":"Scan every point","description":"Iterate through all points so each one can compete for the retained set.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"scans_input_values","scope":"scan-points","readMode":"heap-value-query-v1"}]},"commonMistakes":["Only checking the first k points","Skipping points after the heap first reaches size k"],"hint":"Every point needs one chance to enter the heap.","semanticSpec":{"intent":"Scan the input points so every candidate can be evaluated.","doneWhen":"There is a loop over the point sequence.","shouldFailWhen":"The scan does not traverse the input sequence.","roles":["input scan","current point","candidate evaluation"],"mustProve":["The point sequence is iterated.","Each current point is available to later heap logic."],"mustNotAccept":["Processing only a prefix.","Using a loop unrelated to the input points."],"equivalentVariants":["Loop directly over points.","Loop over point indices and read the current point."],"proofSnippets":[{"id":"py-k-closest-scan-points","language":"python","code":"def kClosest(points, k):\n    heap = []\n    for point in points:\n        current_size = len(heap)"}]}},{"id":"heap-push","title":"Push each point by distance","description":"Compute squared distance and push the current point together with its distance-derived priority.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"pushes_heap_values","scope":"point-distance-push","readMode":"heap-value-query-v1"}]},"commonMistakes":["Using square root instead of squared distance","Pushing only the distance and losing the point coordinates"],"hint":"Store both priority and coordinates so you can return the selected points.","semanticSpec":{"intent":"Insert each current point into the heap with distance-derived priority.","doneWhen":"The current point contributes a heap entry during the scan.","shouldFailWhen":"The code scans points but never inserts a heap entry.","roles":["current point","distance priority","heap insert"],"mustProve":["The priority is derived from x*x + y*y for the current point.","The heap insertion occurs during the point scan.","The inserted heap entry preserves enough point coordinate data to return the selected points later."],"mustNotAccept":["Pushing a constant entry.","Pushing only a distance without retaining point coordinates.","Using a priority unrelated to squared distance."],"equivalentVariants":["Use negative squared distance in a min-heap to simulate a max-heap.","Use a native max-priority queue keyed by squared distance."],"proofSnippets":[{"id":"py-k-closest-push-points","language":"python","code":"import heapq\n\n\ndef kClosest(points, k):\n    heap = []\n    for point in points:\n        x = point[0]\n        y = point[1]\n        dist = x * x + y * y\n        heapq.heappush(heap, [-dist, x, y])"}]}},{"id":"heap-size-check","title":"Evict the farthest retained point","description":"Keep the heap ordered so overflow removal discards the farthest retained candidate.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"maintains_heap_size_bound","scope":"bounded-point-overflow","readMode":"heap-value-query-v1"}]},"commonMistakes":["Popping when the heap size is equal to k","Letting the heap grow beyond k for the rest of the scan","Removing the closest point instead of the farthest retained point"],"hint":"After every push, pop once only when the heap has more than k entries, and make that pop remove the farthest retained candidate.","semanticSpec":{"intent":"Maintain a bounded heap of at most k retained point candidates while ensuring each overflow removes the current farthest retained point.","doneWhen":"Every overflow beyond k triggers a heap pop from a farthest-first retained ordering.","shouldFailWhen":"The heap is allowed to remain larger than k, the size guard uses the wrong bound, or the overflow pop removes a closer retained point.","roles":["heap","size bound k","overflow removal","farthest retained candidate"],"mustProve":["The heap size is compared with k.","A heap pop removes one overflow entry.","The popped overflow entry is the farthest retained candidate under the distance priority."],"mustNotAccept":["Using >= k and dropping too many candidates.","Checking k without popping from the heap.","Popping the closest point instead of the farthest retained point."],"equivalentVariants":["Use negative squared distances in a min-heap so the heap root represents the farthest retained point.","Use a native max-priority queue keyed by squared distance and pop when its size exceeds k.","Use an equivalent strict overflow check that removes the current worst retained candidate."],"proofSnippets":[{"id":"py-k-closest-bound-heap","language":"python","code":"import heapq\n\n\ndef kClosest(points, k):\n    heap = []\n    for point in points:\n        x = point[0]\n        y = point[1]\n        dist = x * x + y * y\n        heapq.heappush(heap, [-dist, x, y])\n        if len(heap) > k:\n            heapq.heappop(heap)"}]}},{"id":"return-points","title":"Return retained points","description":"Return the point coordinates that remain in the bounded heap.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"heap","fact":"returns_heap_result","scope":"return-values","readMode":"heap-value-query-v1"}]},"commonMistakes":["Returning the heap size instead of the retained points","Returning a constant or unrelated list","Dropping the heap result before returning"],"hint":"Project the surviving heap entries back to point coordinates.","semanticSpec":{"intent":"Return the selected points from the bounded heap.","doneWhen":"The function returns a value derived from the retained heap entries.","shouldFailWhen":"The code maintains the heap but returns an unrelated value or never returns the retained points.","roles":["bounded heap","retained entries","returned points"],"mustProve":["The returned value is derived from the heap that stores retained point entries."],"mustNotAccept":["Returning a constant.","Returning an unrelated local collection.","Omitting the final return."],"equivalentVariants":["Use a list comprehension over the heap entries.","Build a result list from the surviving heap entries and return it."],"proofSnippets":[{"id":"py-k-closest-return-points","language":"python","code":"import heapq\n\n\ndef kClosest(points, k):\n    heap = []\n    for point in points:\n        x = point[0]\n        y = point[1]\n        dist = x * x + y * y\n        heapq.heappush(heap, [-dist, x, y])\n        if len(heap) > k:\n            heapq.heappop(heap)\n    return [[entry[1], entry[2]] for entry in heap]"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"Scan once, keep the k nearest in a heap whose top is the farthest, and trim only on overflow.","body":["A bounded heap turns \"find the k closest\" into a single pass: each new point is weighed against the current worst kept candidate, and anything farther is dropped without ever being ranked.","Each push and pop costs log k rather than log n, so the work is O(n log k) time and O(k) space, well under the O(n log n) full sort when k is small."],"takeaways":[{"title":"The root is the candidate to beat","body":"A max-heap keyed by squared distance puts the farthest kept point at the top, so every newcomer is compared against the one point that might be displaced."},{"title":"Trim only on strict overflow","body":"Pop only when a push makes the heap exceed k, so eviction trades a far point for a near one instead of shrinking the kept set below k."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
