Sort Unseen Candidates by Vector Inner Product
Easy · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
A personalization engine represents both a target profile user and N catalog candidates items as integer vectors of common dimension d. For candidate i (0 <= i < N), its affinity value with user is the vector inner product obtained by summing coordinate-wise products across all d positions (user[0] * items[i][0] + ... + user[d - 1] * items[i][d - 1]), where higher values indicate stronger alignment.
You also receive seen, a list of 0-based candidate indices that the user has already interacted with. Implement rank_items(user, items, seen) to return the 0-based indices of all unvisited candidates:
- Exclude every candidate index present in
seen. - Order the remaining candidate indices from highest affinity value to lowest.
- Break equal-affinity ties by placing the smaller 0-based index first.
- Return all
Nindices ranked whenseenis empty, and return[]when every candidate index appears inseen. - All vector coordinates are Python integers, so inner products are exact integers without floating-point rounding.
def rank_items(user: list[int], items: list[list[int]], seen: list[int]) -> list[int]:
Examples
Example 1
Input: user = [3, -1], items = [[1, -1], [2, 0], [2, 2], [0, -5]], seen = []
Output: [1, 3, 0, 2]
Explanation: Candidate inner products are 4, 6, 4, and 5 for indices 0, 1, 2, and 3. Candidate 1 (6) ranks first and candidate 3 (5) second; candidates 0 and 2 tie at 4, so index 0 comes ahead of 2.
Example 2
Input: user = [3, -1], items = [[1, -1], [2, 0], [2, 2], [0, -5]], seen = [1, 0]
Output: [3, 2]
Explanation: Using the same vectors as Example 1, candidates 1 and 0 are omitted because they appear in seen, leaving candidate 3 (5) ahead of candidate 2 (4).
Example 3
Input: user = [-2, 1, 3], items = [[4, 2, 0], [1, 0, 1], [-1, -2, 0], [0, 5, 2]], seen = [3]
Output: [1, 2, 0]
Explanation: Candidate inner products are -6, 1, 0, and 11. Candidate 3 achieves the top value (11) but is skipped because 3 is in seen, leaving [1, 2, 0].
Constraints
1 <= d <= 128, whered = len(user)andlen(items[i]) == dfor every0 <= i < len(items).1 <= len(items) <= 10^4-1000 <= user[j], items[i][j] <= 1000(every inner product lies within[-1.28 * 10^8, 1.28 * 10^8]).0 <= len(seen) <= len(items), with distinct integers in[0, len(items) - 1].
Step-by-step walkthrough
Understand vectors, inner products, and the ranking rules
In personalization pipelines, an embedding is a fixed-length list of numbers capturing the attributes of a profile or a catalog item in a shared
d-dimensional space:user: one list ofdintegers representing the target profile.items:Nlists ofdintegers, whereitems[i]belongs to candidatei.seen: 0-based candidate indices that must be omitted from the output.
A candidate's affinity score is the dot product (inner product) of
useranditems[i]—multiply matching positions pair by pair and sum the products:user = [ 3, -1] items[3] = [ 0, -5] dot product = (3 * 0) + (-1 * -5) = 0 + 5 = 5We need to return a list of original candidate indices obeying three rules:
- Omit every index listed in
seen. - Sort remaining candidates from highest score to lowest score.
- Break equal-score ties by smallest original index first (
0before2).
Because every coordinate is an integer, every dot product is an exact integer—two candidates either tie cleanly or differ by at least
1.Filter seen candidates fast without losing original indices
Two common pitfalls arise when excluding
seencandidates:- Linear list lookups: Both
seenanditemscan hold up to10,000entries. Testingitem_index in seenon a plainlistscansseenfrom index0every time—up to10,000 * 10,000 = 100,000,000comparisons! Convertingseenonce intoseen_set = set(seen)reduces each membership test toO(1)average time. - Renumbered indices: Filtering
itemsinto a shorter list first and callingenumerateafterward renumbers the survivors (0, 1, ...) instead of preserving their original positions initems!
items = [cand_A, cand_B, cand_C, cand_D], seen = {0, 1} WRONG (filter first, then enumerate): filtered = [cand_C, cand_D] --> indices become 0 and 1 (lost original 2 and 3!) RIGHT (enumerate original `items`, skip if index in `seen_set`): (0, cand_A) -> skip (1, cand_B) -> skip (2, cand_C) -> keep 2 (3, cand_D) -> keep 3Checking
if item_index in seen_set: continuebefore computing the dot product also avoids wastedO(d)arithmetic on excluded candidates.- Linear list lookups: Both
Sort with a negated-score tuple to get tie-breaking for free
We need score descending, and on ties index ascending.
Sorting 2-element tuples
(a, b)in Python comparesafirst and falls back tobonly whenaties. Watch what happens on Example 1 (scores = [4, 6, 4, 5], where indices0and2tie at4) if you sort(score, item_index)withreverse=True:WRONG: sort (score, index) with reverse=True Pairs: (4, 0), (6, 1), (4, 2), (5, 3) Sorted: (6, 1), (5, 3), (4, 2), (4, 0) <-- index 2 beats index 0 on ties! RIGHT: sort (-score, index) in ascending order Pairs: (-4, 0), (-6, 1), (-4, 2), (-5, 3) Sorted: (-6, 1), (-5, 3), (-4, 0), (-4, 2) --> indices [1, 3, 0, 2]Negating
scoremaps larger scores to more negative values so top scores sort first (-6 < -5 < -4), while keepingitem_indexpositive preserves smaller-index-first order whenever-scorematches (0 < 2).Write the dot-product helper
Let us write a concise helper
compute_dot_productthat walks matching coordinates viazipand totals their products inO(d)time:def compute_dot_product(vec_a: list[int], vec_b: list[int]) -> int: """Multiply matching coordinates of two equal-length vectors and sum the products.""" total_score = 0 for coord_a, coord_b in zip(vec_a, vec_b): total_score += coord_a * coord_b return total_scoreAssemble `rank_items` phase by phase
Now combine all four phases: construct
seen_set, score each unvisited item into(-score, item_index), sort ascending, and unpack the indices. When every candidate is inseen,scored_candidatesstays[]andrank_itemsreturns[]naturally:def rank_items(user: list[int], items: list[list[int]], seen: list[int]) -> list[int]: # Phase 1: convert `seen` to a set (e.g., {0, 1}) so each membership check is O(1). seen_set = set(seen) # Phase 2: score only unseen items while keeping each item's original index from `enumerate`. # scored_candidates: list of (-score, item_index) tuples, e.g., [(-6, 1), (-5, 3), (-4, 0), (-4, 2)]. scored_candidates: list[tuple[int, int]] = [] for item_index, item_embedding in enumerate(items): # Skip seen items before computing the dot product to avoid wasted O(d) work. if item_index in seen_set: continue score = compute_dot_product(user, item_embedding) scored_candidates.append((-score, item_index)) # Phase 3: sort tuples in ascending order. # Negating `score` puts higher scores first (-6 < -4), while keeping `item_index` positive # breaks equal-score ties by smaller index first ((-4, 0) < (-4, 2)). scored_candidates.sort() # Phase 4: extract the ranked item indices in sorted order. ranked_indices: list[int] = [] for neg_score, item_index in scored_candidates: ranked_indices.append(item_index) return ranked_indicesTrace Example 3 step by step
Let us trace
user = [-2, 1, 3],items = [[4, 2, 0], [1, 0, 1], [-1, -2, 0], [0, 5, 2]], andseen = [3]:seen_set = {3} item_index item_embedding In seen_set? Dot product with [-2, 1, 3] Candidate tuple ---------- --------------- ------------ ----------------------------------- --------------- 0 [ 4, 2, 0] No (-2)*(4) + 1*(2) + 3*(0) = -6 ( 6, 0) 1 [ 1, 0, 1] No (-2)*(1) + 1*(0) + 3*(1) = 1 (-1, 1) 2 [-1, -2, 0] No (-2)*(-1) + 1*(-2) + 3*(0) = 0 ( 0, 2) 3 [ 0, 5, 2] Yes skipped! -- scored_candidates before sort: [(6, 0), (-1, 1), (0, 2)] scored_candidates after sort: [(-1, 1), (0, 2), (6, 0)] ranked_indices returned: [1, 2, 0]Candidate
3would have achieved11(the highest inner product), yet because3belongs toseen_set, it is skipped and[1, 2, 0]is returned.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def compute_dot_product(vec_a: list[int], vec_b: list[int]) -> int: """Multiply matching coordinates of two equal-length vectors and sum the products.""" total_score = 0 for coord_a, coord_b in zip(vec_a, vec_b): total_score += coord_a * coord_b return total_score def rank_items(user: list[int], items: list[list[int]], seen: list[int]) -> list[int]: # Phase 1: convert `seen` to a set (e.g., {0, 1}) so each membership check is O(1). seen_set = set(seen) # Phase 2: score only unseen items while keeping each item's original index from `enumerate`. # scored_candidates: list of (-score, item_index) tuples, e.g., [(-6, 1), (-5, 3), (-4, 0), (-4, 2)]. scored_candidates: list[tuple[int, int]] = [] for item_index, item_embedding in enumerate(items): # Skip seen items before computing the dot product to avoid wasted O(d) work. if item_index in seen_set: continue score = compute_dot_product(user, item_embedding) scored_candidates.append((-score, item_index)) # Phase 3: sort tuples in ascending order. # Negating `score` puts higher scores first (-6 < -4), while keeping `item_index` positive # breaks equal-score ties by smaller index first ((-4, 0) < (-4, 2)). scored_candidates.sort() # Phase 4: extract the ranked item indices in sorted order. ranked_indices: list[int] = [] for neg_score, item_index in scored_candidates: ranked_indices.append(item_index) return ranked_indices✅ Submit now — all tests should pass.
Intuition & how it works
Think of user as a listener's preference profile (say [tempo_weight, acoustic_weight]) and each candidate's embedding (a fixed-length list of numbers encoding an object's attributes) as how strongly that track expresses each attribute. Computing the dot product—multiplying matching coordinates pair by pair and adding them together—condenses each candidate into a single affinity number, and our task is to assemble a leaderboard of original 0-based IDs for candidates absent from seen.
Three common missteps make naive implementations slow or wrong: testing i in seen on a plain list rescans seen in O(N * len(seen)) time; filtering items into a new list before calling enumerate renumbers every remaining candidate; and sorting (score, index) with reverse=True flips the tie-breaker so higher indices beat lower indices when scores match. Instead, we convert seen into a hash set, iterate over enumerate(items) to retain original indices, and sort (-score, item_index) via lexicographic comparison (comparing tuple positions left to right, checking the second element only when the first elements are equal).
Trace Example 2 with user = [3, -1], items = [[1, -1], [2, 0], [2, 2], [0, -5]], and seen = [1, 0]:
- Convert
seenintoseen_set = {0, 1}. - Walk
enumerate(items): indices0and1belong toseen_set(skip); candidate2scores3*2 + (-1)*2 = 4-> append(-4, 2); candidate3scores3*0 + (-1)*(-5) = 5-> append(-5, 3). - Sort
[(-4, 2), (-5, 3)]ascending ->[(-5, 3), (-4, 2)], and read out[3, 2].
Complexity
- Time:
O(N + m * d + m log m), whereN = len(items),d = len(user), andmis the count of unvisited candidates (O(N * d + N log N)in the worst case whenseenis empty). Constructingseen_settakesO(len(seen))time, scanningenumerate(items)performsNO(1)set lookups and evaluatesmdot products of dimensiond(O(m * d)), and sortingmtuples takesO(m log m)comparisons. - Space:
O(N)extra memory becauseseen_set,scored_candidates, andranked_indiceseach hold at mostNentries, independent of dimensiond.
Edge cases
- Empty
seen(seen = []): Every candidate is unvisited, so allNindices are scored and sorted. - Every candidate seen (
len(seen) == len(items)): All entries are skipped,scored_candidatesstays[], andrank_itemsreturns[]. - All scores equal (e.g.,
useris all zeros): Every unvisited candidate receives-score = 0, so sorting(0, item_index)preserves ascending index order. - All negative scores: Negating
-1and-5produces1and5; since1 < 5,-1still ranks ahead of-5. - Extreme integer scores near
±1.28 * 10^8: Atd = 128with coordinates up to±1000, neighboring scores like127,001,000and127,000,999differ by1. Python arbitrary-precisionintarithmetic avoids overflow and rounding collisions. - Arbitrary ordering inside
seen:set(seen)treats[3, 1]and[1, 3]identically.
Common mistakes
- Sorting
(score, item_index)withreverse=True: Reversing the entire tuple comparison reverses the tie-breaker too, putting(4, 2)ahead of(4, 0). (Sorting indices viakey=lambda i: scores[i], reverse=Truedoes keep0before2thanks to Python's stable sort—a sort that preserves input order on ties—whereas bundlingitem_indexinside a reversed tuple actively inverts ties.) - Filtering
itemsprior toenumerate: Building a filtered list of vectors first discards their original 0-based positions initems. - Testing
item_index in seenon alist: WhenN = 10^4andlen(seen) = 5000, repeated linear scans perform~5 * 10^7redundant comparisons. - Default quicksort or
float32in NumPy: NumPy's defaultnp.argsortis not stable on ties (kind="stable"is required), andfloat32only stores integers exactly up to2^24 = 16,777,216, collapsing distinct scores near1.28 * 10^8(int64stays exact).
Alternative approaches
Vectorized NumPy implementation. Using int64 arrays prevents overflow and float rounding, matrix-vector multiplication @ evaluates all N inner products in C, np.argsort(-scores, kind="stable") orders highest scores first while keeping smaller indices first on ties, and a boolean mask removes seen indices:
import numpy as np
def rank_items_numpy(user: list[int], items: list[list[int]], seen: list[int]) -> list[int]:
scores = np.asarray(items, dtype=np.int64) @ np.asarray(user, dtype=np.int64)
ranked_all = np.argsort(-scores, kind="stable")
is_unseen = np.ones(len(items), dtype=bool)
is_unseen[np.asarray(seen, dtype=np.int64)] = False
return ranked_all[is_unseen[ranked_all]].tolist()
Its asymptotic bound is O(N * d + N log N) (even though @ scores seen items too, single-call vectorized C math is typically faster in wall-clock time than per-item Python loops).
Follow-up questions
- How would you reduce the runtime if the caller only wants the top
kunseen candidates rather than the entire sorted list? Passscored_candidatestoheapq.nsmallest(k, scored_candidates), which maintains a size-kmin-heap (a binary-tree priority queue that updates the bestktuples inO(log k)time per candidate) to extract the topk(-score, item_index)entries inO(m log k)time with identical tie-breaking. In NumPy,np.argpartition(-scores, k - 1)isolates the topkitems inO(N)expected time before anO(k log k)sort of just thosekwinners (paying attention to boundary ties at thek-th score if strict index tie-breaking is needed). - How would you serve top recommendations in a few milliseconds when the catalog contains millions of item vectors? Exhaustive
O(N * d)scoring per request is too slow at million-item scale, so production retrieval layers index item vectors in an approximate maximum inner-product search (MIPS) structure (such as HNSW graphs or quantized inverted files in FAISS or ScaNN) to inspect only high-affinity regions in sublinear time. To excludes = len(seen)visited items without rebuilding the index per user, query the index for the topk + scandidates and filter outseen_setin memory—at mostsreturned hits can be seen, guaranteeing at leastkunseen candidates remain. - Under what circumstances is cosine similarity preferable to an unnormalized inner product for comparing embeddings? A vector's L2 norm is its Euclidean length (
sqrt(sum(x^2))), and cosine similarity divides the inner product by both vectors' L2 norms so only the angle between them matters. Unnormalized inner products naturally boost items with large vector norms, whereas cosine similarity compares pure directional alignment so high-norm popular items do not drown out niche items; in practice, always match the similarity metric used during model training, since dot-product-trained models intentionally encode baseline item quality or popularity in the vector norm.
Follow-up questions
- How would you reduce the runtime if the caller only wants the top `k` unseen candidates rather than the entire sorted list?
- How would you serve top recommendations in a few milliseconds when the catalog contains millions of item vectors?
- Under what circumstances is cosine similarity preferable to an unnormalized inner product for comparing embeddings?
Similar questions
- Chain Lowercase Words by Overlapping Endpoints
- Order-Preserving Deduplication and Boundary Word Merging
- Expected Tosses for Consecutive Heads-Tails
- Customer Spend and Daily Revenue Metrics
- A/B Test Design for an In-App Recommendation Widget
- Model Fit Diagnostics, Skewed Classes, and Missing Features
More Yahoo interview questions
- Model Fit Diagnostics, Skewed Classes, and Missing Features Easy
- Expected Tosses for Consecutive Heads-Tails Easy
- Customer Spend and Daily Revenue Metrics Medium Pro
- A/B Test Design for an In-App Recommendation Widget Medium Pro
- Chain Lowercase Words by Overlapping Endpoints Medium Pro
- Uniform Sum Check for Relabeled Dice Medium Pro
- Order-Preserving Deduplication and Boundary Word Merging Medium Pro