We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard design problem, graded against 5 test cases (2 of them hidden).
Build a working data structure to an API - LRU caches, rate limiters, and iterators.
Reach for it when you see: "Design a class supporting these operations in O(1)" - an API rather than a single function.
More Designproblems →State per user:
- `tweets`: array of `(timestamp, tweetId)`, append-only.
- `following`: `Set<userId>`.
`postTweet`: `tweets[userId].push((globalTick++, tweetId))` in O(1).
`getNewsFeed(userId)`: collect the followed-set ∪ {userId}. For each one, take the *last* entry of their tweets list (the most recent). Push those into a max-heap keyed by timestamp. Pop 10 times; each pop, push the next-older entry from the same user. This is the k-way merge of sorted lists. With k followees and limit 10, the cost is `O((k + 10) log k)` ≈ `O(k log k)` per feed read.
`follow / unfollow`: hash-set operations, O(1).
Why heap-on-read instead of fanout-on-write? With this small problem we don't have to push tweets into followers' inboxes at write time. In a real system, fanout-on-write trades higher write cost for O(1) reads; fanout-on-read (this approach) trades the opposite. Twitter uses a hybrid: fanout-on-write for normal users, fanout-on-read for celebs (so a tweet from a 100M-follower account doesn't trigger 100M writes).
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.