CD0020 AI Code Comprehension

Mode D · AI-Assisted 60 Min NumPy · Python 3 3 Phases · 3 AI Flaws

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 (n_queries, d) or (d,) input and returns an (n_queries, n_vecs) float64 matrix. Its values must equal the reference loop’s values within 10^{-12}, and no Python loop over stored rows is allowed.
(2) topk(queries, k): returns (ids, scores), each of shape (m, \min(k, n)), 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)
Three-phase round: Phase 1 read and explain the starter module unaided, Phase 2 prompt the AI to vectorize score() and add topk(), Phase 3 audit a draft containing three unnamed flaws shown as question marks; below, three contract boxes for score(), topk(), and the loop-versus-vectorized parity oracle

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.

Interactive PyTorch Workspace: Switch to the split-screen workspace to run the Phase 1 warm-up, steer the simulated assistant, and audit its draft against the hidden parity, ordering, and dtype checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
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 m queries and n 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)
Stage map with two rows: the starter's reference loop (input queries, norms in the loop marked with a question mark, per-pair score, sort, rank output) and the AI draft pipeline (input queries, input prep, score matrix, and ordering each marked with a question mark, then the topk and rank output), joined by a parity check arrow

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:

Phase 1 (Read & Explain): How many times do lines 29-30 execute for 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?
Phase 2 (Spotting Flawed Prompts): Do not judge prompts by coverage of the score formula alone. Check whether the spec pins all three contracts: row normalization, descending order with stable ties, and float64 end to end. A contract the prompt drops comes back dropped in the regenerated draft.
Phase 3 (Auditing the Cosine Scorer): Scale one stored row by 10: should its cosine score change, and does it in the draft’s 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?
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 *