Design Twitter
Design a simplified Twitter with post, follow, unfollow, and news feed. Think about: How to efficiently retrieve the 10 most recent tweets? Hint: Consider using a heap to merge sorted tweet lists. Example: post_tweet(1, 5) get_news_feed(1) → [5] follow(1, 2) post_tweet(2, 6) get_news_feed(1) → [6, 5] (most recent first)
Design Twitter tests whether you can keep a best-so-far structure honest as you go. Interviewers love it because it reveals your priority-based reasoning and your edge-case discipline. The trap is stale entries or unbalanced structures—be clear about what belongs in the heap.
Examples
You write
Twitter: post_tweet(user_id: int, tweet_id: int), get_news_feed(user_id: int), follow(follower_id: int, followee_id: int), unfollow(follower_id: int, followee_id: int)
Example 1
- Input
- Twitter(), postTweet(1, 5), getNewsFeed(1) => [5], follow(1, 2), postTweet(2, 6), getNewsFeed(1) => [6, 5], unfollow(1, 2), getNewsFeed(1) => [5]
- returns
- [[5], [6, 5], [5]]
Example 2
- Input
- Twitter(), postTweet(1, 1), postTweet(2, 2), postTweet(1, 3), getNewsFeed(1) => [3, 1], follow(1, 2), getNewsFeed(1) => [3, 2, 1]
- returns
- [[3, 1], [3, 2, 1]]
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsLinked Lists
I reach for it when
- Nodes point to the next node, and you cannot index into the list.
- You must reverse, merge, reorder or remove a node.
Say this before you type. Say which pointers you hold and which link you are about to change.
All 12 Linked Lists problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.