← Questions

Bag-of-words similarity search from scratch

0
AppleCodingLast asked Aug 2025

A coding interview question asked in Apple's technical phone screen, last asked Aug 2025. It tests text processing, similarity and search.

Build a small text similarity search engine with no libraries. You write each function: tokenize text, turn documents into bag-of-words vectors (raw counts or TF-IDF), score similarity, and return the documents closest to a query.

Part 1: tokenize

  • tokenize(text: str, stopwords: set[str] | None = None, stem: bool = False) -> list[str]: lowercase with Unicode-aware case folding, keep runs of letters and digits as tokens (other characters split them), drop stopwords, and optionally apply a simple suffix stemmer. Justify your choices.

Part 2: vectors

  • build_vectors(doc_ids, docs: list[list[str]], use_tfidf: bool) -> dict[str, dict[str, float]]: sparse vectors. Raw term counts, or count × idf, with idf(t) = ln((N + 1) / (df(t) + 1)) + 1.

Part 3: similarity

  • similarity(a, b, metric) -> float: cosine similarity (0.0 if either vector is all zero), or Jaccard similarity over the sets of terms with non-zero weight.

Part 4: search

  • top_k(doc_ids, docs, query_tokens, k) -> list[tuple[str, float]]: TF-IDF vectors for documents and the query, cosine similarity, only scores above 0, highest first, ties by smaller doc ID.

Example

tokenize("Running dogs JUMPED, the cat sits!", {"the"})
  ->  ["running", "dogs", "jumped", "cat", "sits"]

build_vectors(["a", "b"], [["red", "red", "fox"], ["fox", "den"]], True)
  ->  {"a": {"red": 2.81093, "fox": 1.0}, "b": {"fox": 1.0, "den": 1.405465}}   # rounded to 6 places

similarity({"red": 3, "fox": 1}, {"red": 1, "den": 1}, "cosine")   ->  0.67082    # 3 / sqrt(20)
similarity({"red": 3, "fox": 1}, {"red": 1, "den": 1}, "jaccard")  ->  0.333333

top_k(["d1", "d2", "d3"], [["red", "fox", "fox"], ["fox", "den"], ["blue", "den"]], ["fox", "den"], 2)
  ->  [("d2", 1.0), ("d1", 0.590852)]

Constraints

  • Up to 10^4 documents and 2 * 10^5 tokens in total.
  • Text may include accented letters, other scripts, punctuation and emoji.

Clarifying questions

  • Which characters count as part of a word, and how should non-Latin scripts tokenize?
  • Should query terms that never appear in the corpus be ignored?
  • How many queries per corpus: is indexing time or query time more important?

What a strong answer covers

  • Sparse dictionaries throughout; cosine computed by iterating the smaller vector.
  • Precomputed document norms, so a query costs O(terms in matching documents).
  • Complexity of indexing and of each query.
  • How to scale: an inverted index so only documents sharing a term are scored, pruning, approximate nearest-neighbor search over dense embeddings.

Follow-ups

  • Replace TF-IDF with BM25.
  • Add phrase or bigram matching.
  • Index a corpus that doesn't fit in memory.

Where it's asked

  • Apple · Technical phone screen · Last asked Aug 2025

What it tests

text processing · similarity · search

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding