Picture a retrieval-evaluation codebase on a Google team. An offline harness ranks a few hundred thousand stored document embeddings against each eval query by cosine similarity and reports recall@k. This round follows the code-comprehension format reported for Google’s 2026 interviews. You receive a module you did not write, an AI assistant is available, and the grade depends on how you read, steer, and audit, not on typing speed.
Phase 1 (Read & Explain, unaided, no AI): trace what SimilarityIndex computes and name the lines where its cost lives. Then fix the one correctness issue your trace exposes. After an ingest batch in which the upstream encoder timed out on a few documents, every ranking the harness prints contains nan scores, the order is visibly non-monotone, and NumPy emits a RuntimeWarning about an invalid value encountered in a divide.
Phase 2 (AI-Assisted Optimize): write the prompt that gets the assistant to vectorize the row-wise similarity loop and add a top-k API. Phase 3 (Audit the AI’s Rewrite): the assistant’s draft runs and returns arrays of the right shape, yet it violates the contract below in exactly three places. Find them, fix them in place, and write one verification test proving that the vectorized path matches the reference loop within tolerance.
Phase 2 Target Contract:
(1) score(queries): accepts an or
input and returns an
float64 matrix. Its values must equal the reference loop’s values within
, and no Python loop over stored rows is allowed.
(2) topk(queries, k): returns (ids, scores), each of shape , with the best match first. Equal scores are broken by insertion order, exactly as
rank() breaks them today, and scores are float64.
(3) rank(query, k): keeps its current return format, a list of (id, score) pairs, and delegates to topk().
Starter Module (42 Lines, Read Before You Touch):
01 import numpy as np
02
03
04 class SimilarityIndex:
05 """Cosine-similarity index over an in-memory vector store."""
06
07 def __init__(self, dim: int):
08 self.dim = dim
09 self.ids = []
10 self.vecs = np.empty((0, dim), dtype=np.float64)
11
12 def add(self, ids, vecs):
13 vecs = np.asarray(vecs, dtype=np.float64)
14 assert vecs.ndim == 2 and vecs.shape[1] == self.dim
15 assert len(ids) == vecs.shape[0]
16 self.ids.extend(ids)
17 self.vecs = np.vstack([self.vecs, vecs])
18
19 def score(self, queries):
20 """Return an (n_queries, n_vecs) matrix of cosine similarities."""
21 queries = np.asarray(queries, dtype=np.float64)
22 n_queries, n_vecs = queries.shape[0], self.vecs.shape[0]
23 sims = np.zeros((n_queries, n_vecs), dtype=np.float64)
24 for i in range(n_queries):
25 q = queries[i]
26 query_norm = np.linalg.norm(q)
27 for j in range(n_vecs):
28 v = self.vecs[j]
29 vec_norm = np.linalg.norm(v)
30 sims[i, j] = np.dot(q, v) / (query_norm * vec_norm)
31 return sims
32
33 def rank(self, query, k=None):
34 """Return top-k (id, score) pairs, best match first."""
35 sims = self.score(np.asarray(query)[None, :])[0]
36 order = sorted(range(len(sims)), key=lambda j: -sims[j])
37 if k is not None:
38 order = order[:k]
39 return [(self.ids[j], sims[j]) for j in order]
40
41 def __len__(self):
42 return len(self.ids)
Figure 1: The round runs read, steer, audit in that order. The Phase 2 target contract along the bottom is the yardstick for both your prompt and the AI’s draft.
1Inspection Checklist (Where to Look)
(1) Explain Before You Touch: State in one sentence what sims[i, j] means and what rank() returns, including how it orders equal scores.
(2) Complexity Hot Spot: Count how many times the innermost lines run for queries and
stored rows, and which per-row work repeats for every query.
(3) Degenerate Rows: Decide what a cosine score should be when a vector has no magnitude, before trusting any ranking built on it.
(4) Same Quantity, Fewer Loops: A vectorized score must reproduce every factor of line 30, not just the part that looks like a matmul.
(5) Output Contract: Order, tie-break, shape, and dtype are all part of the API that downstream tests pin.
2Visual Review Map (Figure 2)

Figure 2: The reference loop (top) and the AI draft (bottom) as stage maps. Every ? marks a stage to audit, and deciding what each stage should do is the exercise.
3Interviewer Nudge & Line Focus
Work the three phases in order using the stage checks below:
n_queries queries and n_vecs stored rows, which norm gets recomputed once per query, and what does line 30 evaluate to when a stored row has no magnitude at all?
score()? Which direction does np.argsort order each row by default, and which of two tied rows must come first? Then trace the dtype of every intermediate: what does a float64 golden-score assertion receive?
Leave a Reply