Implement TF–IDF with sparse matrices

Quick Overview

This question tests a candidate's practical understanding of information retrieval and natural language processing by requiring a from-scratch implementation of TF–IDF vectorization. It evaluates proficiency in numerical computing, sparse matrix construction, and algorithm design — skills commonly assessed for data science and machine learning engineering roles.

Implement TF–IDF with sparse matrices

Company: Thumbtack

Role: Data Scientist

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

Implement TF–IDF from scratch. Given a list of documents (strings), build a memory-efficient tokenizer (lowercase, strip punctuation, optional min_df/max_df filtering), compute term frequencies, smoothed IDF = log((1 + N) / (1 + df)) + 1, and output a CSR sparse matrix (rows=documents, cols=vocabulary ordered lexicographically). Requirements: (1) do not use external NLP libraries; only Python, NumPy, and SciPy are allowed; (2) handle OOV tokens at transform time by ignoring them; (3) support L2 normalization per row; (4) provide an inverse_transform(doc_index) that reconstructs the top-k terms by TF–IDF score; (5) analyze time and space complexity for fit and transform; and (6) write a unit test showing correctness on a 3-document toy corpus with repeated terms.

Overview: This question tests a candidate's practical understanding of information retrieval and natural language processing by requiring a from-scratch implementation of TF–IDF vectorization. It evaluates proficiency in numerical computing, sparse matrix construction, and algorithm design — skills commonly assessed for data science and machine learning engineering roles.

Read the full Thumbtack Data Scientist interview experience this question came from

Thumbtack logo
Thumbtack
Oct 13, 2025
mediumData ScientistOnsiteCoding & Algorithms
24
0

Implement TF–IDF from Scratch (Python + NumPy/SciPy)

You are given a list of documents (plain strings). Implement a TF–IDF vectorizer from scratch — no scikit-learn, no external NLP libraries — that turns the corpus into a sparse document–term matrix you could feed to a downstream model.

Your vectorizer must support the following behavior:

  1. Tokenization and preprocessing. Lowercase the text, strip punctuation, and tokenize using a memory-efficient (streaming / generator-based) tokenizer. No external NLP libs.
  2. Vocabulary and filtering. Support optional min_df and max_df document-frequency filtering. Each threshold may be an integer (an absolute number of documents) or a float in (0,1](0, 1] (a fraction of documents). The vocabulary (the matrix columns) must be ordered lexicographically for deterministic output.
  3. TF–IDF computation. Term frequency (TF) is the raw count of a term in a document. Use the smoothed IDF idft=log⁡ ⁣(1+N1+dft)+1\text{idf}_t = \log\!\left(\frac{1 + N}{1 + \text{df}_t}\right) + 1 where NN is the number of documents and dft\text{df}_t is the number of documents containing term tt . Output a SciPy CSR sparse matrix of shape (n_documents, vocab_size) .
  4. Transform behavior. At transform time, ignore out-of-vocabulary (OOV) tokens. Support optional L2 row normalization (each document vector scaled to unit length).
  5. API surface. Expose a class with fit , transform , fit_transform , and inverse_transform(doc_index, k=None) , where inverse_transform returns the top- kk terms for a document ranked by TF–IDF score (if k is None , return all non-zero terms sorted by score descending).
  6. Complexity. Analyze the time and space complexity of fit and transform in terms of the number of documents, total tokens, and vocabulary size.
  7. Unit test. Provide a unit test that checks correctness on a 3-document toy corpus containing repeated terms.

Constraints & Assumptions

  • Allowed dependencies: Python standard library, NumPy, and SciPy only — no scikit-learn, NLTK, spaCy, or other NLP libraries.
  • Input is an iterable of strings. Assume it fits the streaming model: transform may re-iterate the corpus, so a re-iterable container (e.g. a list ) is acceptable; a one-shot generator passed to a separate fit then transform would be consumed — call out this assumption.
  • Handle empty documents gracefully (all-zero rows).
  • Output must be deterministic : identical input yields identical column order and values across runs.
  • Token definition can be assumed to be runs of lowercase alphanumeric characters ( [a-z0-9]+ ) unless the interviewer specifies otherwise — state your choice.

Clarifying Questions to Ask Guidance

  • How should tokens be defined — alphanumeric runs only, or keep apostrophes/hyphens (e.g. "don't", "state-of-the-art")? Should digits be kept or dropped?
  • What TF variant is expected — raw count (as stated), log-scaled 1+log⁡(tf)1 + \log(\text{tf}) , or sublinear? (The prompt specifies raw count; confirm.)
  • Should transform accept a fresh corpus (unseen documents), or only re-encode the fitted corpus? This drives whether OOV handling is exercised.
  • Is idf defined exactly as given (the scikit-learn smoothed form), or should I support the unsmoothed variant log⁡(N/df)\log(N/\text{df}) as well?
  • What is the expected scale (number of documents, vocabulary size)? This decides whether per-document count caching in fit_transform is acceptable or whether memory must stay bounded.

What a Strong Answer Covers Guidance

  • Correct, working code that compiles and passes the toy test: a class with fit / transform / fit_transform / inverse_transform , a streaming tokenizer, and a SciPy CSR output of the right shape.
  • Faithful IDF and TF semantics : smoothed IDF exactly as specified, raw-count TF, and df computed from unique terms per document (not raw counts).
  • Correct vocabulary handling : lexicographic column order, min_df / max_df resolved correctly for both int and float, OOV tokens dropped at transform time, L2 normalization applied per row and safe on zero rows.
  • Sparse-structure fluency : building CSR via (data, indices, indptr) rather than densifying; awareness of canonical column ordering and why it matters.
  • Complexity analysis that separates tokenization cost ( O(T)O(T) ), the O(Vlog⁡V)O(V \log V) vocabulary sort, and the O(nnz)O(\text{nnz}) matrix assembly — in terms of documents DD , tokens TT , vocabulary VV , and non-zeros.
  • Robustness : empty documents, empty corpus, all-OOV documents, and the max_df < min_df misconfiguration all handled deliberately.
  • A meaningful unit test : asserts vocabulary order, specific IDF values, matrix shape/nnz, OOV behavior, normalized row norms ≈1\approx 1 , and inverse_transform ranking.

Follow-up Questions Guidance

  • How would you scale this to a corpus that does not fit in memory (tens of millions of documents)? Discuss the hashing trick (feature hashing) as an alternative to an explicit vocabulary, and the time/space trade-offs of dropping inverse_transform .
  • The current transform requires the corpus to be re-iterable. How would you restructure fit_transform to make a single streaming pass, and what does that cost in peak memory?
  • TF–IDF treats terms independently and ignores order. What would change if you needed n-grams (bigrams/trigrams), and how does that affect vocabulary size and sparsity?
  • How would you compute cosine similarity between two documents directly from the CSR matrix, and why does L2 normalization make that a simple dot product?
  • The smoothed IDF gives a term appearing in every document an IDF of log⁡ ⁣(1+N1+N)+1=1\log\!\big(\tfrac{1+N}{1+N}\big) + 1 = 1 , not 00 . Why might you prefer that over an unsmoothed IDF that zeroes such terms out?