Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

CODING CHALLENGE · N°12

TF-IDF

Medium AI EngineeringNLPRetrieval

The scoring that ran search for decades — and still seeds hybrid retrieval today. It rewards a word that is frequent in one document but rare across the corpus, and shrugs off words that appear everywhere. No numpy, just a logarithm.

The problem

Implement TF-IDF: the weight of a term in one document of a corpus. The corpus is a list of documents, each a list of tokens; doc_index selects the document. Term frequency is the term's share of that document: tf = count(term in doc) / len(doc). Inverse document frequency uses how many documents contain the term (df) out of N total: idf = log(N / df). Return tf · idf. If the term is absent from the document, its weight is 0.

SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? open the hints under the problem, or Reveal solution is one click away.

YOUR TASK

Implement tf_idf(corpus, doc_index, term). Return tf · idf for the term in the selected document — the term's share of that doc, scaled by how rare it is across the corpus.

CPython · WebAssembly
Examples and constraints 4 examples
EXAMPLE 1
Input corpus=[['a','b'],['a','c'],['a','d']], doc_index=0, term='a'
Output 0.0
'a' is in every doc → idf = log(1) = 0 → weight 0
EXAMPLE 2
Input corpus=[['a','a','b','c'],['d'],['e']], doc_index=0, term='a'
Output 0.5493061443340549
tf = 2/4, idf = log(3) → a rare, frequent term scores high
EXAMPLE 3
Input corpus=[['a','b'],['c']], doc_index=0, term='z'
Output 0.0
term not in the document → weight 0
EXAMPLE 4
Input corpus=[[], ['a']], doc_index=0, term='a'
Output 0.0
edge case: an empty document scores 0 instead of dividing by zero
CONSTRAINTS
  • Term frequency: tf = count(term in doc) / len(doc).
  • Document frequency df = number of documents containing the term; idf = log(N / df) with N = len(corpus) (natural log).
  • If the term is absent from the document, return 0 (so you never divide by df = 0).
  • Pyodide has no numpy — use the math stdlib and plain lists only.
Hints 4 ideas
HINTS — 4 IDEAS
  1. tf = (times the term appears in the doc) / (number of tokens in the doc).
  2. If tf is 0 the whole weight is 0 — return early, and you avoid a df = 0 divide.
  3. df = how many documents contain the term at all; idf = log(N / df) with N = len(corpus).
  4. A term in every document has df = N, so idf = log(1) = 0 — it carries no weight.
Approach, complexity & discussion — open after you solve

Start from brute force

The tempting shortcut counts document frequency as the number of times the term occurs anywhere in the corpus, in one pass over every token: O(T) time for T tokens and O(1) space. It is wrong, because IDF asks how many documents contain the term. For [["a", "a", "a"], ["b"]] it gives df = 3 and idf = log(2/3), a negative weight, instead of log(2/1). The correct per-call scan has a cost problem of its own: scoring every term of every document by calling it once per pair rescans the corpus each time, O(D · V · T) for D documents with V distinct terms each.

The approach

Compute the two factors exactly as defined, and return early whenever the answer is already 0. The reference tf_idf takes doc = corpus[doc_index] and returns 0.0 for an empty document, which avoids dividing by len(doc) = 0. Then tf = doc.count(term) / len(doc), the term’s share of the document. If tf == 0 the term is absent and the weight is 0, so it returns before touching the corpus.

That early return is also what makes the IDF safe. Once tf > 0, the selected document contains the term, so df = sum(1 for d in corpus if term in d) is at least 1 and math.log(len(corpus) / df) is always defined. Because df never exceeds N, the IDF is never negative, and it is exactly 0 for a term found in every document. term in d counts each document once, however many times the term repeats inside it. The result is tf * idf; the TypeScript tfIdf does the same with filter and includes.

corpus (term = a)contains a?0: a a b c1: d2: eyesnonotf = 2 / 4 = 0.5df = 1 of N = 3idf = ln(3/1) = 1.0986tf * idf = 0.5493df counts documents, not occurrences:a is twice in doc 0 but adds 1 to df
The traced example as data. tf is read from the selected document alone; df asks one yes/no question of every document. Only the product of the two is the weight, so a term must be both frequent here and rare overall to score high.

Walk through an example

The second example is the one where both factors are non-zero: corpus = [["a", "a", "b", "c"], ["d"], ["e"]], doc_index = 0, term = "a".

stepquantityvalue
1doc["a", "a", "b", "c"], length 4, not empty
2tf = doc.count("a") / len(doc)2 / 4 = 0.5, not 0, so continue
3df, documents containing "a"1 (only document 0)
4idf = math.log(3 / 1)1.0986122886681098
5tf * idf0.5493061443340549

Complexity

One weight costs O(T) time for T tokens in the corpus: doc.count scans the document, and term in d scans each document list once. Extra space is O(1). Building a whole TF-IDF table by repeating that call per document and term is O(D · V · T); precomputing every df in one pass brings the table down to O(T).

Edge cases to test

  • corpus = [["a", "b"], ["a", "c"], ["a", "d"]], term "a" → 0.0. A term in every document has idf = log(1) = 0, whatever its frequency.
  • corpus = [["a", "b"], ["z"]], document 0, term "z" → 0.0. The term exists elsewhere, but it is absent from this document, so the weight is 0.
  • corpus = [["a", "b"], ["c"]], term "z" → 0.0. The term is in no document; returning early avoids log(N / 0).
  • corpus = [[], ["a"]], document 0 → 0.0. The empty-document guard prevents dividing by len(doc) = 0.
  • corpus = [["a", "a", "a"], ["b"]], term "a" → 0.6931471805599453, which is 1.0 × log 2. Counting occurrences instead of documents makes df = 3 and the weight negative.
  • corpus = [["A", "b"], ["a"]], document 0, term "a" → 0.0. Tokens match exactly, so "A" is not "a"; lowercase during tokenization if case should not matter.

Common mistakes

  • Using raw term frequency without IDF — common words then dominate every document.
  • Computing df before checking tf — for a term absent from every document df is 0 and log(N / 0) divides by zero; return 0 early or use a smoothed IDF.
  • Skipping document-length normalization, so long documents score artificially high.

Follow-ups an interviewer asks next

Compute TF-IDF for every term in every document.
Make one pass to build document frequencies, adding 1 to df[t] for each t in set(doc), and keep a Counter per document for the raw counts. Every weight is then a dictionary lookup and two arithmetic operations, so the whole table costs O(T) time. Store it as sparse vectors, because most terms do not appear in most documents.
Rank documents for a multi-word query.
Build an inverted index from each term to the documents that contain it, with their term frequencies. Score a document as the sum of tf · idf over the query terms, touching only documents in those postings lists. Normalizing each document’s TF-IDF vector, so the score becomes a cosine similarity, stops long documents from winning just by containing more words.
Which IDF formula do real libraries use?
Variants exist because log(N / df) is 0 for a term in every document and undefined for one in none. scikit-learn’s default is ln((1 + N) / (1 + df)) + 1, which acts as if one extra document contained every term, so no IDF is ever 0 or undefined. A sublinear TF, 1 + log(count), is another common change, so 20 occurrences do not count 20 times as much as one.

Where this shows up

TF-IDF is the classic lexical weighting that BM25 refines with saturation and length normalization, and it is still the baseline for keyword search, document-similarity, and as features for text classification. It is the “rare words carry the signal” intuition made quantitative.

In practice the weight is never computed one term at a time. A document becomes a sparse vector, one dimension per vocabulary word, holding its TF-IDF weight for each word it contains and an implicit 0 everywhere else. A vocabulary can run to hundreds of thousands of words while a short document uses a few hundred, so storing only the non-zero entries is what makes the representation affordable. Two documents are then compared by the cosine of the angle between their vectors, which only involves the words they share; normalizing each vector to length 1 first turns that cosine into a plain dot product.

Search engines turn the same table sideways into an inverted index: for each word, the list of documents that contain it, with the in-document count. The length of that list is exactly df, so IDF comes for free, and a query only reads the lists for its own words instead of scanning the corpus. This is the structure BM25 scores over too, which is why swapping one formula for the other does not change the index.

Two other uses are worth knowing. Sorting one document’s terms by weight and keeping the top few is a crude but serviceable keyword extractor, because the top of that list is words the document repeats and the rest of the corpus does not. And TF-IDF vectors fed to a linear model, logistic regression or a linear SVM, are the standard first baseline for text classification: they train in seconds, and their per-word coefficients can be read directly. In modern retrieval systems, lexical scores like TF-IDF and BM25 often run next to dense embedding search, because exact matching catches rare identifiers, part numbers and names that an embedding can blur together.

What TF-IDF cannot do is know that two different words mean the same thing: “car” and “automobile” are orthogonal dimensions, so a document using one scores 0 for a query using the other. It also ignores word order, so “dog bites man” and “man bites dog” get identical vectors. Those two blind spots are exactly what embeddings were introduced to address.

Check yourself

What does tf_idf([["x", "y"], ["x", "x", "z"], ["w"]], 1, "x") return, to four decimals?

0.2703. Document 1 has 3 tokens, two of them x, so tf = 2/3. x is in documents 0 and 1, so df = 2 and idf = ln(3/2) ≈ 0.4055. The product is 0.27031007207210955.

For [["a", "b"], ["c"]], term "a" in document 0 scores 0.3466. What happens if you append a third document ["d"]?

It rises to 0.5493. Document 0 did not change, so tf stays 0.5, but N grows to 3 while df stays 1, so idf goes from ln 2 to ln 3. Appending a copy of document 0 instead raises df to 2 as well and drops the weight to 0.2027: rarity is always relative to the whole corpus.

In [["a", "b"], ["c"]], term "b" in document 0 scores 0.3466. Document 0 becomes ["a", "a", "b"]. What is b’s weight now, and why did it move?

0.2310. The count of b is unchanged and so is its df, but the document is now 3 tokens long, so tf falls from 1/2 to 1/3. Dividing by the document length is what stops long documents from scoring high just by containing more words.

You need the weight of one term in all D documents. What does calling tf_idf D times cost when every document contains the term, and how do you do better?

Each call rescans the corpus for df, so it is O(D · T) for T total tokens. The df does not depend on which document you score: compute it once in O(T), then each document’s tf costs only its own length, for O(T) in total.

Reference solution

Reference solution — Python
import math

def tf_idf(corpus, doc_index, term):
    doc = corpus[doc_index]
    if len(doc) == 0:
        return 0.0
    tf = doc.count(term) / len(doc)
    if tf == 0:
        return 0.0  # absent term → no weight (and no df=0 divide)
    df = sum(1 for d in corpus if term in d)
    idf = math.log(len(corpus) / df)
    return tf * idf


print(tf_idf([['a', 'b'], ['a', 'c'], ['a', 'd']], 0, 'a'))     # -> 0.0 (in every doc)
print(tf_idf([['a', 'a', 'b', 'c'], ['d'], ['e']], 0, 'a'))     # ~0.5493
Reference solution — TypeScript
function tfIdf(corpus: string[][], docIndex: number, term: string): number {
  const doc = corpus[docIndex];
  if (doc.length === 0) return 0;
  const tf = doc.filter((t) => t === term).length / doc.length;
  if (tf === 0) return 0; // absent term → no weight (and no df=0 divide)
  const df = corpus.filter((d) => d.includes(term)).length;
  const idf = Math.log(corpus.length / df);
  return tf * idf;
}

console.log(tfIdf([["a", "b"], ["a", "c"], ["a", "d"]], 0, "a")); // -> 0 (in every doc)
console.log(tfIdf([["a", "a", "b", "c"], ["d"], ["e"]], 0, "a")); // ~0.5493

Questions about TF-IDF

What does TF-IDF measure?

TF-IDF measures how characteristic a word is of one document within a collection. Term frequency is the share of the document made up of that word, so a word the document repeats scores higher. Inverse document frequency is the logarithm of the total number of documents divided by the number that contain the word, so a word found everywhere scores near zero and a rare one scores high. Multiplying them rewards words that are frequent here but rare elsewhere, which is why TF-IDF picks out topic words and ignores words like the and of.

Why does TF-IDF use a logarithm for inverse document frequency?

The raw ratio of total documents to documents containing the term ranges from 1 to N, so without a log a word seen in one document out of a million would weigh a million times more than a ubiquitous one, and rarity would swamp everything else. The logarithm compresses that range: each time a term becomes ten times rarer, its weight grows by the same fixed amount. It also makes a term that appears in every document score exactly zero. Karen Sparck Jones introduced inverse document frequency in 1972, and the logarithmic form has been standard since.

Why is the TF-IDF of a word that appears in every document zero?

Because its inverse document frequency is the log of N divided by N, and the log of 1 is 0. Multiplying any term frequency by 0 gives 0. That is the intended behavior: a word present in every document cannot tell documents apart, so it should carry no weight in search or comparison. In the first example, a appears in all three documents, so its weight is 0 even though it makes up half of document 0. Smoothed variants used by libraries give such words the lowest IDF instead of exactly zero.

What is the difference between TF-IDF and BM25?

BM25 keeps the idea of inverse document frequency but changes how term frequency counts. In TF-IDF, ten occurrences count ten times as much as one; BM25 saturates, so each extra occurrence adds less, controlled by a parameter usually called k1. BM25 also normalizes by document length relative to the corpus average, controlled by a parameter b, so a long document does not win just by containing more words. Values of k1 between 1.2 and 2.0 with b around 0.75 are common starting points, and BM25 is the default ranking function in many search engines.

▶  Watch it explained
Finished this one? 0 / 76 Challenges done
NextBM25 Scoring Next on the “RAG & retrieval” ladder · rung 4 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Challenges