← Questions

TF-IDF scoring for documents

0
AppleCodingLast asked Dec 2025

A coding interview question asked in Apple's technical phone screen, last asked Dec 2025. It tests information retrieval and text processing.

Implement a simplified TF-IDF scorer. Given a list of documents and a query, score every document against the query and return the document indices from best to worst.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • rank(docs: list[str], query: str) -> list[int]: every index exactly once, by descending score; ties go to the smaller index.

Definitions:

  • Tokens: lowercase the text, split on any character that is not a letter or digit, drop empty tokens.
  • tf(t, d): how many times token t occurs in document d.
  • df(t): how many documents contain t at least once.
  • idf(t) = ln((N + 1) / (df(t) + 1)) + 1, where N is the number of documents.
  • score(d) = sum of tf(t, d) * idf(t) over the query's tokens. A token repeated in the query counts each time.

Example

docs  = ["The cat sat.", "A dog; a DOG!", "cat and dog"]
query = "dog cat"
idf(cat) = idf(dog) = ln(4/3) + 1 ≈ 1.2877
scores ≈ [1.2877, 2.5754, 2.5754]
rank(docs, query) -> [1, 2, 0]      # 1 and 2 tie; the smaller index first

Constraints

  • 1 <= len(docs) <= 10^4; up to about 2 * 10^6 tokens in total.
  • Text may contain punctuation and digits.

Clarifying questions

  • How are repeated query terms treated?
  • Natural log or another base? (It changes scores, not the order, when every term shares the base.)
  • Should documents with score 0 be returned?

What a strong answer covers

  • One pass to count tf per document and df only for query terms, then a second pass to score. O(total tokens) time.
  • Memory: keep only the counts you need, not a full matrix.
  • A stable, explicit sort key (-score, index).
  • Tests: case and punctuation, a query term in no document, repeated query terms, empty documents.

Follow-ups

  • Many queries against the same documents: build an inverted index and score only documents that contain a query term.
  • Normalize by document length (cosine or BM25).
  • Return only the top k.

Where it's asked

  • Apple · Technical phone screen · Last asked Dec 2025

What it tests

information retrieval · text processing

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