Design a News Feed
Show the newest posts from people a user follows, the design question often called Design Twitter.
DSA, Medium, Heap / Priority Queue
Which structure or algorithm, and what does it cost.
Build a class FeedService. post(user, post_id) publishes a post. follow(user, other) makes user follow other; following yourself, or someone already followed, changes nothing. unfollow(user, other) undoes it; unfollowing someone you do not follow changes nothing. feed(user) returns the ids of the 5 newest posts by user and everyone user follows, newest first, or fewer if fewer exist. Newer means a later call. The example input is the list ops of calls in order, each as a list. Return the list of what each feed call returned.
Examples
Constraints
- 1 <= number of calls <= 100,000.
- User numbers and post ids are whole numbers between 1 and 1,000,000, and all post ids are different.
- A user can follow any number of other users.
Your answer must contain
- The simple method and its cost; the heap merge and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(1) per post, follow and unfollow, and O(f log f) per feed for f followed users.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Each user's own posts are already in time order. Think about what that gives you when you combine several users.
Hint 2 the approach
You need only the newest few posts overall. Take them one at a time from whichever user has the newest unused post.
Hint 3 the key step
Use a max-heap holding the newest post of each source, keyed by time. Pop the best, then push that user's next older post. Stop after five.
Walkthrough
Full walkthrough brute force to best
Brute force
On each feed call, gather every post by the user and everyone followed, sort them by time, and take the newest 5. This sorts all history for each call, so it costs O(P log P) for P posts gathered, and P keeps growing.
Better method
Gather only the 5 newest posts of each source, sort that pile by time, and keep the newest 5. At most 5f posts are sorted, so a call costs O(f log f). It works, but it collects and sorts many posts that never reach the feed.
Best method
Each user's posts are stored in time order, so their newest post is at the end of their list. Put the newest post of the user and of each followed user in a max-heap keyed by time. Pop the newest, add it to the feed, and push the next older post of the same user. Stop after 5 posts or when the heap is empty. This is a merge of sorted lists, and it touches only about f + 5 posts, but filling the heap still costs O(f log f), so its gain over the 5f sort is smaller memory per call, not a lower bound. A global counter gives every post its time. Post is an append, and follow and unfollow change a set, so all three are constant time.
Hand trace
Run on the calls of example 1. Posts get times 1, 2 and 3: user 1 has post 10 at time 1, and user 2 has post 20 at time 2 and post 21 at time 3. User 1 follows user 2. Feed for user 1: the heap holds the newest post of user 1 (time 1) and of user 2 (time 3). Pop time 3, so post 21 joins the feed, and push user 2's older post (time 2). Pop time 2, so post 20 joins. User 2 has no older post. Pop time 1, so post 10 joins. The feed is [21, 20, 10]. After the unfollow, the heap holds only user 1's post 10, so the feed is [10]. The result is [[21, 20, 10], [10]].
Code
import heapq
class FeedService:
def __init__(self):
self.clock = 0
self.posts = {} # user -> list of (time, post_id), oldest first
self.follows = {} # user -> set of followed users
def post(self, user, post_id):
self.clock += 1
self.posts.setdefault(user, []).append((self.clock, post_id))
def follow(self, user, other):
if user != other:
self.follows.setdefault(user, set()).add(other)
def unfollow(self, user, other):
self.follows.get(user, set()).discard(other)
def feed(self, user):
heap = [] # newest post of each source, keyed by negated time
for u in self.follows.get(user, set()) | {user}:
p = self.posts.get(u)
if p:
heapq.heappush(heap, (-p[-1][0], u, len(p) - 1))
out = []
while heap and len(out) < 5:
_, u, i = heapq.heappop(heap)
out.append(self.posts[u][i][1])
if i > 0:
heapq.heappush(heap, (-self.posts[u][i - 1][0], u, i - 1))
return outTime and memory
A post, follow or unfollow takes O(1). A feed call takes O(f log f) for f sources: building the heap costs up to f pushes, and at most 5 pops and 5 pushes follow. Memory is O(P) for P posts plus the follow sets.
Common mistakes
- Merging by post id instead of time. Ids need not rise with time, so keep a counter.
- Forgetting the user's own posts. The feed includes them even when the user follows nobody.
- Letting a self-follow or an unfollow of a stranger change the state. Those calls must do nothing, and a set handles both.
- Pushing every post of every followed user into the heap. Push only each user's newest post, then the next older one when needed.