Top TF-IDF Terms of a Document
A search team wants the most distinctive words of one document. Tokenise every document by lower-casing it and taking maximal runs of the characters a-z and 0-9 as words.
For a term t in document docIndex: tf = (count of t in that document) / (number of tokens in that document) and idf = Math.log(N / df), where N is the number of documents and df the number of documents containing t. The score is tf * idf.
Return up to k terms of that document with a score greater than 0, sorted by score descending and then alphabetically. Terms that appear in every document score 0 and are never returned.
Example 1
Input: docs = ["The cat sat. The cat ran!","The dog sat","the bird flew"], docIndex = 0, k = 2 Output: ["cat","ran"] Explanation: "the" is in every document; "cat" appears twice in document 0 and only there.
Example 2
Input: docs = ["alpha beta","alpha beta"], docIndex = 1, k = 3 Output: []
Constraints
- 1 <= docs.length <= 1000
- Each document has at most 10^4 characters
- 1 <= k <= 100
Hint 1
Count document frequency with a Set of terms per document.
Hint 2
Sort with (a, b) => b.score - a.score || (a.term < b.term ? -1 : 1).
Good practice for: Data Scientist, Machine Learning Engineer, AI Engineer (LLM & Generative AI), MLOps Engineer, Data Engineer, Backend Developer
Run checks your code on 3 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.