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 N indices ranked when seen is empty, and return [] when every candidate index appears in seen.
  • 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, where d = len(user) and len(items[i]) == d for every 0 <= 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

  1. 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 of d integers representing the target profile.
    • items: N lists of d integers, where items[i] belongs to candidate i.
    • seen: 0-based candidate indices that must be omitted from the output.

    A candidate's affinity score is the dot product (inner product) of user and items[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 = 5
    

    We need to return a list of original candidate indices obeying three rules:

    1. Omit every index listed in seen.
    2. Sort remaining candidates from highest score to lowest score.
    3. Break equal-score ties by smallest original index first (0 before 2).

    Because every coordinate is an integer, every dot product is an exact integer—two candidates either tie cleanly or differ by at least 1.

  2. Filter seen candidates fast without losing original indices

    Two common pitfalls arise when excluding seen candidates:

    1. Linear list lookups: Both seen and items can hold up to 10,000 entries. Testing item_index in seen on a plain list scans seen from index 0 every time—up to 10,000 * 10,000 = 100,000,000 comparisons! Converting seen once into seen_set = set(seen) reduces each membership test to O(1) average time.
    2. Renumbered indices: Filtering items into a shorter list first and calling enumerate afterward renumbers the survivors (0, 1, ...) instead of preserving their original positions in items!
    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 3
    

    Checking if item_index in seen_set: continue before computing the dot product also avoids wasted O(d) arithmetic on excluded candidates.

  3. 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 compares a first and falls back to b only when a ties. Watch what happens on Example 1 (scores = [4, 6, 4, 5], where indices 0 and 2 tie at 4) if you sort (score, item_index) with reverse=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 score maps larger scores to more negative values so top scores sort first (-6 < -5 < -4), while keeping item_index positive preserves smaller-index-first order whenever -score matches (0 < 2).

  4. Write the dot-product helper

    Let us write a concise helper compute_dot_product that walks matching coordinates via zip and totals their products in O(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_score
    
  5. Assemble `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 in seen, scored_candidates stays [] and rank_items returns [] 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_indices
    
  6. Trace 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]], and seen = [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 3 would have achieved 11 (the highest inner product), yet because 3 belongs to seen_set, it is skipped and [1, 2, 0] is returned.

  7. 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]:

  1. Convert seen into seen_set = {0, 1}.
  2. Walk enumerate(items): indices 0 and 1 belong to seen_set (skip); candidate 2 scores 3*2 + (-1)*2 = 4 -> append (-4, 2); candidate 3 scores 3*0 + (-1)*(-5) = 5 -> append (-5, 3).
  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), where N = len(items), d = len(user), and m is the count of unvisited candidates (O(N * d + N log N) in the worst case when seen is empty). Constructing seen_set takes O(len(seen)) time, scanning enumerate(items) performs N O(1) set lookups and evaluates m dot products of dimension d (O(m * d)), and sorting m tuples takes O(m log m) comparisons.
  • Space: O(N) extra memory because seen_set, scored_candidates, and ranked_indices each hold at most N entries, independent of dimension d.

Edge cases

  • Empty seen (seen = []): Every candidate is unvisited, so all N indices are scored and sorted.
  • Every candidate seen (len(seen) == len(items)): All entries are skipped, scored_candidates stays [], and rank_items returns [].
  • All scores equal (e.g., user is all zeros): Every unvisited candidate receives -score = 0, so sorting (0, item_index) preserves ascending index order.
  • All negative scores: Negating -1 and -5 produces 1 and 5; since 1 < 5, -1 still ranks ahead of -5.
  • Extreme integer scores near ±1.28 * 10^8: At d = 128 with coordinates up to ±1000, neighboring scores like 127,001,000 and 127,000,999 differ by 1. Python arbitrary-precision int arithmetic avoids overflow and rounding collisions.
  • Arbitrary ordering inside seen: set(seen) treats [3, 1] and [1, 3] identically.

Common mistakes

  • Sorting (score, item_index) with reverse=True: Reversing the entire tuple comparison reverses the tie-breaker too, putting (4, 2) ahead of (4, 0). (Sorting indices via key=lambda i: scores[i], reverse=True does keep 0 before 2 thanks to Python's stable sort—a sort that preserves input order on ties—whereas bundling item_index inside a reversed tuple actively inverts ties.)
  • Filtering items prior to enumerate: Building a filtered list of vectors first discards their original 0-based positions in items.
  • Testing item_index in seen on a list: When N = 10^4 and len(seen) = 5000, repeated linear scans perform ~5 * 10^7 redundant comparisons.
  • Default quicksort or float32 in NumPy: NumPy's default np.argsort is not stable on ties (kind="stable" is required), and float32 only stores integers exactly up to 2^24 = 16,777,216, collapsing distinct scores near 1.28 * 10^8 (int64 stays 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 k unseen candidates rather than the entire sorted list? Pass scored_candidates to heapq.nsmallest(k, scored_candidates), which maintains a size-k min-heap (a binary-tree priority queue that updates the best k tuples in O(log k) time per candidate) to extract the top k (-score, item_index) entries in O(m log k) time with identical tie-breaking. In NumPy, np.argpartition(-scores, k - 1) isolates the top k items in O(N) expected time before an O(k log k) sort of just those k winners (paying attention to boundary ties at the k-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 exclude s = len(seen) visited items without rebuilding the index per user, query the index for the top k + s candidates and filter out seen_set in memory—at most s returned hits can be seen, guaranteeing at least k unseen 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

Similar questions

More Yahoo interview questions

All 8 Yahoo questions →