Bag-of-words count vectors
Build bag-of-words count vectors for a set of documents over a fixed vocabulary. Given docs (a list of documents, each a list of word tokens) and vocab (the ordered vocabulary list, assumed to have no duplicates), return for each document a vector of length len(vocab) where position i is the number of times vocab[i] appears in that document. Words not in the vocabulary are ignored. Return the list of count vectors in document order.
Implement
bag_of_words(docs: list[list[str]], vocab: list[str]) → list[list[int]]Examples
in
[[["a","b","a"],["b","c"]],["a","b","c"]]out[[2,1,0],[0,1,1]]What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 15 min
solution.py
InputExpectedGot
[[["a","b","a"],["b","c"]],["a","b","c"]][[2,1,0],[0,1,1]]not run yetsample