Heap-Based KNN Classifier and Regressor

Quick Overview

Implement exact k-nearest-neighbour search in pure Python with a fixed-size heapq max-heap, then build a majority-vote classifier and a mean regressor on top of it. Tests heap key design, deterministic tie-breaking, input validation and per-query complexity.

Heap-Based KNN Classifier and Regressor

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `k_nearest(train_X, query, k)`, returning the `k` nearest training points by Euclidean distance as a list of `(index, distance)` tuples sorted by distance, then index (ties go to the lower index). Track candidates with a `heapq` max-heap of size `k`. Build `knn_classify(train_X, train_y, queries, k)` (majority vote; when votes tie, the smallest label wins) and `knn_regress(train_X, train_y, queries, k)` (mean of the neighbours' targets as a `float`) on top. Both return one prediction per query as a list. For example: ```python k_nearest([[0, 0], [3, 4], [1, 1], [-2, 0]], [0, 0], 3) # [(0, 0.0), (2, 1.4142...), (3, 2.0)] knn_classify([[0.0], [1.0], [3.0]], [2, 1, 1], [[0.4]], 2) # [1] (labels 2 and 1 tie, smallest wins) knn_regress([[0], [1], [2], [10]], [1, 2, 3, 100], [[9.0]], 3) # [35.0] ``` ```hint Max-heap from a min-heap `heapq` only provides a min-heap. Decide what key to store so that `heap[0]` is the worst candidate you are currently keeping. ``` ```hint Equal distances Training points arrive in index order. Work out whether a newcomer at the same distance as the current worst should ever replace it. ``` ### Constraints & Assumptions - `k` must be an `int` in `[1, len(train_X)]`, otherwise raise `ValueError`. - `len(train_X) != len(train_y)` or a point dimension mismatch raises `ValueError`. - Points are lists of finite numbers. Labels are mutually comparable. - Python standard library only (`heapq`, `math` and `Counter` are imported). No NumPy. ### What a Strong Answer Covers - A size-`k` heap whose root is the current worst neighbour, with a precise condition for when a new point replaces it - Tie handling: the lower index for equal distances and the smallest label for tied votes - Validation of `k` (including Python's `bool`), of mismatched `train_X` and `train_y` lengths, and of dimension mismatches - Per-query time and space complexity compared with sorting every distance - Output types: sorted `(index, distance)` tuples, one label per query, and `float` regression values ### Follow-up Questions - What is the complexity per query, and why is the heap better than sorting? - How would you add distance-weighted voting? - How would this scale to millions of training points?

Overview: Implement exact k-nearest-neighbour search in pure Python with a fixed-size heapq max-heap, then build a majority-vote classifier and a mean regressor on top of it. Tests heap key design, deterministic tie-breaking, input validation and per-query complexity.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement k_nearest(train_X, query, k), returning the k nearest training points by Euclidean distance as a list of (index, distance) tuples sorted by distance, then index (ties go to the lower index). Track candidates with a heapq max-heap of size k. Build knn_classify(train_X, train_y, queries, k) (majority vote; when votes tie, the smallest label wins) and knn_regress(train_X, train_y, queries, k) (mean of the neighbours' targets as a float) on top. Both return one prediction per query as a list.

For example:

k_nearest([[0, 0], [3, 4], [1, 1], [-2, 0]], [0, 0], 3)
# [(0, 0.0), (2, 1.4142...), (3, 2.0)]

knn_classify([[0.0], [1.0], [3.0]], [2, 1, 1], [[0.4]], 2)
# [1]   (labels 2 and 1 tie, smallest wins)

knn_regress([[0], [1], [2], [10]], [1, 2, 3, 100], [[9.0]], 3)
# [35.0]

Constraints & Assumptions

  • k must be an int in [1, len(train_X)] , otherwise raise ValueError .
  • len(train_X) != len(train_y) or a point dimension mismatch raises ValueError .
  • Points are lists of finite numbers. Labels are mutually comparable.
  • Python standard library only ( heapq , math and Counter are imported). No NumPy.

What a Strong Answer Covers Guidance

  • A size- k heap whose root is the current worst neighbour, with a precise condition for when a new point replaces it
  • Tie handling: the lower index for equal distances and the smallest label for tied votes
  • Validation of k (including Python's bool ), of mismatched train_X and train_y lengths, and of dimension mismatches
  • Per-query time and space complexity compared with sorting every distance
  • Output types: sorted (index, distance) tuples, one label per query, and float regression values

Follow-up Questions Guidance

  • What is the complexity per query, and why is the heap better than sorting?
  • How would you add distance-weighted voting?
  • How would this scale to millions of training points?