FastPrepCompute TF-IDF Scores
Problems/Compute TF-IDF Scores

Compute TF-IDF Scores

Apple logoApple● MediumNEW GRADPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report asks for simple TF-IDF but gives no formula, tokenization or examples. The judged core task matches the source at about 65%.

Compute the TF-IDF score of term in each document, in input order. Documents are already normalized into lowercase words separated by single spaces; match whole words exactly.

  • TF is the number of occurrences of term in a document divided by that document's word count.
  • df is the number of documents containing term at least once.
  • If df > 0, use IDF = ln(N / df), where N is the number of documents and ln is the natural logarithm. Do not add smoothing.
  • The score is TF * IDF. An empty document scores zero. If df is zero, every score is zero.

Return an empty array for an empty corpus. Floating-point answers use a relative-or-absolute tolerance of 10^-6.

Function

tfIdf(documents: String[], term: String) → double[]

Examples

Example 1

documents = ["cat cat dog","dog"]term = "cat"return = [0.46209812037329684,0.0]

There are 2 documents and cat appears in 1, so IDF is ln(2). Its term frequency in the first document is 2/3 and in the second is 0.

Example 2

documents = ["cat","cat dog"]term = "cat"return = [0.0,0.0]

The term appears in every document, so IDF is ln(1) = 0.

Constraints

  • 0 <= documents.length <= 100
  • 0 <= documents[i].length <= 2000
  • 1 <= term.length <= 20
  • Each document is empty or contains lowercase English words separated by exactly one space, without leading or trailing spaces. Each word and term contains 1 to 20 lowercase English letters.

More Apple problems

  • Evaluate DivisionPHONE SCREEN · Seen Nov 2026
  • Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
  • Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
All Apple interview questionsSee Apple hiring insights
Saved
public double[] tfIdf(String[] documents, String term) {
    // Write your code here.
}
Checking account…