---
title: Exact cosine top-k retrieval
url: https://gurkanozkan.ai/learn/coding/mle-exact-cosine-top-k-retrieval-25/
markdown: https://gurkanozkan.ai/learn/coding/mle-exact-cosine-top-k-retrieval-25.md
kind: coding
difficulty: Easy
topics:
  - Retrieval
  - Embeddings
  - RecSys
json: https://gurkanozkan.ai/api/learn/coding/mle-exact-cosine-top-k-retrieval-25.json
robots: noindex
---

# Exact cosine top-k retrieval

Return the indices of the `k` items with the highest cosine similarity to `query`, in descending order of similarity, with ties broken by lower index. Items with zero norm are never returned. If fewer than `k` valid items exist, return all valid ones. A zero-norm query raises `ValueError`.

## Signature

```python
def cosine_top_k(query, items, k: int) -> list[int]: ...
```

## Examples

Each call and the value it should give.

```python
>>> cosine_top_k([1.0, 0.0], [[1.0, 0.0],[0.0, 1.0],[2.0, 0.1]], 2) == [0, 2]
True

>>> cosine_top_k([1.0, 1.0], [[1.0, 1.0],[2.0, 2.0],[1.0, 0.0]], 2) == [0, 1]
True
```

## Hints

1. Normalise the vectors once, then vectorised dot products.
2. Use argpartition for the k highest scores, then sort them descending (ties -> lower index).
3. Zero-norm items are never returned; a zero-norm query raises ValueError.

## Reference solution

```python
import numpy as np

def cosine_top_k(query, items, k):
    q = np.asarray(query, float); M = np.asarray(items, float)
    qn = np.linalg.norm(q)
    if qn == 0:
        raise ValueError("zero query")
    sims = []
    for i, v in enumerate(M):
        n = np.linalg.norm(v)
        if n == 0:
            continue
        sims.append((-(v @ q) / (n * qn), i))
    sims.sort()
    return [i for _, i in sims[:k]]
```

## What a strong solution covers

- Normalises once and computes vectorised dot products.
- `argpartition` for O(n) selection, then sorts k.
- Handles zero vectors.
- Discusses ANN indexes (HNSW, IVF-PQ), the recall/latency trade-off, and pre-normalised storage.

## Common mistakes

- dividing by zero for zero vectors
- a full sort when k ≪ n (discussion).
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
