CD0013 KNN Array Query

Mode B · Build & Trace 30 Min NumPy 4 Array Blanks

A Google data-quality job runs two measurement pipelines that log integer readings of the same quantity — a source-attribution task reported from a Google AI/ML coding round in November 2025. Source A is a tightly calibrated sensor, while source B is a cheap sensor with a much wider spread. A stream of new readings arrives without provenance, and for each one you must decide which source more likely produced it. Naive nearest-distance reasoning picks the wrong source, so the brief asks you to handle ties explicitly and to compare at least two assignment strategies.

You receive A of shape (n_A,), B of shape (n_B,), and queries of shape (Q,), all integer arrays whose dtype is not guaranteed to be signed. Label 0 means source A and label 1 means source B. You may use NumPy only: scikit-learn neighbors, scipy.spatial.distance.cdist, and a Python loop over queries are all off limits. The batched driver returns four arrays of shape (Q,): the kNN labels, the kNN vote margin (share of B votes minus share of A votes, in absolute value, so it lies in [0, 1]), the z-score labels, and the z-score gap |z_A - z_B|.

Complete the 4 missing pieces in the skeleton below and trace the exact array shape after each line. Then argue which strategy is more defensible when one source is much noisier than the other, and verify your module on a synthetic two-source fixture with known ground truth.

Skeleton Code (Fill Blanks 1-4):

01  import numpy as np
02
03
04  def pairwise_dist(queries, pool):
05      # TODO (Blank 1): |queries_i - pool_j| for every query/pool pair, float (Q, N)
06      dists = ...
07      return dists
08
09
10  def knn_vote(dists, pool_labels, k):
11      # TODO (Blank 2): majority label among the k nearest pool points per row;
12      #                 a tied vote falls back to the single nearest label
13      pred, frac_b = ...
14      return pred, frac_b                     # (Q,) int, (Q,) share of B votes
15
16
17  def zscore_assign(queries, A, B, eps=1e-12):
18      # TODO (Blank 3): |queries - mean| per source, scaled by that source std (ddof=0)
19      z_A, z_B = ...
20      return (z_A > z_B).astype(int), z_A, z_B    # 1 = source B, z tie goes to A
21
22
23  def classify(queries, A, B, k=5):
24      A, B = np.asarray(A, float), np.asarray(B, float)
25      pool_labels = np.concatenate([np.zeros(len(A)), np.ones(len(B))]).astype(int)
26      # TODO (Blank 4): all queries at once (no Python loop), labels + margins
27      knn_pred, knn_margin, z_pred, z_margin = ...
28      return knn_pred, knn_margin, z_pred, z_margin
Operator contract for the two-source query classifier: an inputs box holding source arrays A and B plus the query stream feeds two question-marked branches, pairwise distances followed by a kNN vote with a tie rule, and a scale-aware score per source; both branches feed a question-marked step that returns labels and margins for every query. Below, boxes list the forbidden library calls, the allowed NumPy building blocks, and the test oracle

Figure 1: the inputs and the four returned arrays are fixed, and the two assignment strategies run side by side. Every question-marked step is yours to write in plain NumPy.

Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the hidden kNN and z-score checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Broadcast Axes: Decide which axis indexes queries and which indexes pool points before you subtract, and check what integer dtype the readings arrive in.
(2) Row-Wise Neighbors: The k nearest points must be chosen independently for every query row, and equal distances need an order that is identical on every run.
(3) Scale Contract: Each source distance must be measured in that source’s own spread, including a source whose readings never vary.
(4) Batch Contract: One vectorized pass over all queries, labels aligned with the pool order, a neighbor count that may exceed the pool, and margins computed per query.

2Visual Review Map (Figure 2)
Shape trace for the two-source classifier: the top row marks the target shapes of Blanks 1 and 2, from the query and pool vectors to a question-marked (Q, N) distance matrix, a question-marked (Q, k) neighbor set, and per-query outputs; the bottom row marks the target shapes of Blanks 3 and 4, from the sources to per-query standardized distances, per-query margins, and four returned arrays of shape (Q,)

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce, and writing the NumPy ops that reach them is the exercise.

3Interviewer Nudge & Line Focus

Pin the input shape, output shape, and dtype of each blank before writing the NumPy op:

Blank 1 (Pairwise Distances): queries is (Q,) and pool is (N,). Which axis must each array gain so the subtraction broadcasts to (Q, N), and what silently happens instead when Q == N? If both arrays arrive as uint8 sensor counts, what does 3 - 5 evaluate to?
Blank 2 (kNN Vote + Tie Rule): Along which axis does argsort sort a (Q, N) matrix by default, and does slicing its result with [:k] keep the first k rows or the first k columns? With k = 4 and a 2-2 split, which single neighbor should decide, and which sort kind keeps equal integer distances in pool order on every run?
Blank 3 (Scale-Aware Score): Source A has std 2 and source B has std 15. A query sits 8 units from mean A and 12 units from mean B: what are the two standardized distances, and does the winner differ from the raw-distance winner? What does your expression return when every reading of a source is identical?
Blank 4 (Batched Driver + Margins): In which order must A and B be concatenated so the pool lines up with labels on line 25? What should happen when k exceeds n_A + n_B, and how many distinct values can the vote margin take for a fixed k?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *