Rank Documents by Query Relevance with Smoothed TF-IDF
Arrays & HashingAuto-graded · 23 test casesLast updated
Tests hashing and counting over text: tokenize, compute smoothed IDF for query terms, score every document, and sort by descending score with an index tie-break.
Rank Documents by Query Relevance
You have a collection of text documents and a search query. Score each document against the query using a smoothed TF-IDF formula, then report the document positions from most to least relevant.
Tokenization
Apply the same procedure to every document and to the query:
- Convert the text to lowercase.
- A token is a maximal run of consecutive Unicode letters or digits. Every other character, including the underscore
_, separates tokens. - Empty tokens are never produced.
Scoring
Let N be the number of documents and tokens(x) the token list of a text x (repeats kept).
-
Term frequency:
tf(t, d)is the number of times tokentoccurs in documentd. -
Document frequency:
df(t)is the number of documents that containtat least once. -
Smoothed inverse document frequency (natural logarithm):
idf(t) = ln((N + 1) / (df(t) + 1)) + 1 -
Score of a document
dfor queryq: sum over every tokentin the query token list, repeats included:score(d, q) = Σ tf(t, d) · idf(t)
A query token that occurs twice in the query therefore contributes twice. A query token that appears in no document contributes nothing.
Task
Return a list containing every document index 0 … N-1 exactly once, ordered by score from highest to lowest. If two documents have equal score, the one with the smaller index comes first. Documents with score 0 (including empty documents) are still included, at the end, in index order. If the query has no tokens, every score is 0.
Function
Implement rank_by_tfidf(docs, query), where docs is a list of strings and query is a string. It returns a list of integers.
Constraints
1 <= len(docs) <= 10^4- The total number of tokens across all documents is at most about
2 * 10^6 - Documents and the query may be empty strings or contain punctuation and mixed case
- Use the natural logarithm and ordinary floating-point arithmetic
Examples
Example 1
Input: rank_by_tfidf(['red apple', 'green apple', 'banana'], 'apple')
Output: [0, 1, 2]
Example 2
Input: rank_by_tfidf(['The quick brown fox', 'quick blue hare', 'slow turtle'], 'quick')
Output: [0, 1, 2]
Example 3
Input: rank_by_tfidf(['cat cat dog', 'dog bird', 'fish'], 'cat dog')
Output: [0, 1, 2]
Example 4
Input: rank_by_tfidf(['', 'one two', 'three'], 'missing term')
Output: [0, 1, 2]
Hints
Hint 1
Only tokens that occur in the query can change a score, so you do not need counts for any other word.
Hint 2
Count query tokens with multiplicity first. Then make one pass over the documents, counting only query tokens, and update df once per document for each query term present.
Hint 3
Compute scores in a fixed term order so identical documents get identical floats, then sort indices with the key (-score, index).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Only tokens that appear in the query can affect a score, so there is no need to build a full vocabulary or a document-term matrix.
- Tokenize the query and count each term's multiplicity. The score sums over the query's token list, so a repeated query term counts once per repeat.
- If the query has no tokens, every score is 0 and the answer is
[0, 1, ..., N-1]. - Make one pass over the documents. For each document, count only tokens that belong to the query set. This gives
tf(t, d)for every query term. For each query term present in the document, add 1 todf(t). - Compute
idf(t) = ln((N + 1) / (df(t) + 1)) + 1for each query term. - Score each document as the sum, over query terms in a fixed order, of
tf * query_multiplicity * idf. - Sort indices by the key
(-score, index).
Why it is correct
- Each document token is examined once, so
tfis exact. A document adds todf(t)exactly when its count fortis positive, which matches the definition of document frequency. - Terms outside the query never appear in the score formula, so ignoring them changes nothing.
- A query term found in no document has
tf = 0everywhere and adds 0. The+1smoothing means no division by zero can happen. idf >= 1always, so scores are non-negative. A document scores 0 exactly when it has no query term, and such documents fall at the end in index order.- The sort key puts higher scores first and uses the smaller index to break ties. Summing in the same fixed term order for every document means documents with identical term counts get bit-identical floats, so the tie-break is reliable.
Complexity
Let L be the total text length, Q the number of distinct query terms, and N the number of documents.
- Time:
O(L + N·Q + N log N). Tokenizing is linear, each token needs one hash lookup, scoring costsO(Q)per document, and sorting costsO(N log N). - Space:
O(N·Q)in the worst case for per-document query-term counts, plusO(N)for scores.
Reference solution
import math
import re
from collections import Counter
from typing import List
_TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE)
def _tokenize(text: str) -> List[str]:
return _TOKEN_RE.findall(text.lower())
def rank_by_tfidf(docs: List[str], query: str) -> List[int]:
n = len(docs)
query_counts = Counter(_tokenize(query))
if not query_counts:
return list(range(n))
terms = list(query_counts) # fixed order for deterministic float sums
term_set = set(terms)
doc_counts = []
df = dict.fromkeys(terms, 0)
for doc in docs:
counts = Counter(tok for tok in _tokenize(doc) if tok in term_set)
doc_counts.append(counts)
for t in counts:
df[t] += 1
idf = {t: math.log((n + 1) / (df[t] + 1)) + 1 for t in terms}
scores = []
for index, counts in enumerate(doc_counts):
score = sum(counts[t] * query_counts[t] * idf[t] for t in terms)
scores.append((score, index))
scores.sort(key=lambda item: (-item[0], item[1]))
return [index for _, index in scores]