Drop near-duplicate chunks

Drop near-duplicate chunks

Perplexity RAG Interview Question

Retrieval over a corpus with reprinted articles returns the same passage several times, which wastes the context window on text the model has already seen.

Write a function dedupe(chunks, threshold) that keeps a chunk only when its similarity to every chunk already kept is below the threshold. Compare words in lower case, keep the original text, and keep the chunks in the order they arrived.

Note

A,B=the distinct words of two chunksA, B = \text{the distinct words of two chunks}
similarity(A,B)=∣A∩B∣∣A∪B∣\text{similarity}(A, B) = \frac{\lvert A \cap B \rvert}{\lvert A \cup B \rvert}

Asked of

  • AI Engineer
  • ML Engineer
  • Data Scientist

Example 1

Input

chunks = ["the cat sat", "The Cat Sat", "the cat ran away"], threshold = 0.6

Output

["the cat sat", "the cat ran away"]

Example 2

Input

chunks = ["alpha beta", "gamma delta"], threshold = 0.5

Output

["alpha beta", "gamma delta"]

Explanation

In the first example the second chunk shares every word with the first, so its similarity is 1 and it is dropped. The third shares "the" and "cat" out of five distinct words, which is 0.4 and below the threshold, so it is kept.

Submit also runs 2 hidden test cases that check edge cases.

Similar questions