Amazon sells millions of products on its website, and for better customer experience, it wants to show a widget with the most popular items bought on the home page.
I’d like you to tell me how you’d go about calculating the top-k popular items sold on Amazon.
You can assume that you have a service, and your service gets notified in the form of a {customerId, itemId, timestamp} message whenever a customer purchases an item.
这道题考察的是高频商品的实时统计与 Top-K 维护。核心思路通常是先用哈希表按 itemId 统计每个商品的购买次数,再结合最小堆、桶排序或定期聚合来维护前 K 名;如果是流式场景,还要考虑消息持续到达、并发更新、去重以及窗口统计等工程细节。面试中最好先澄清是全量历史 Top-K,还是按时间窗口的 Top-K,因为这会直接影响数据结构和更新策略。