CodeArchon

mediumHeap / Priority QueueTwitterFacebookAmazon

Streaming Timeline Hub

A micro-blogging backend fans in tweets from a user and everyone they follow, surfacing the 10 most recent in merged order.

Design a Twitter-like class supporting postTweet, getNewsFeed (top 10 recent tweets from user + followees), follow, unfollow.

Choose approach

post U1/T101
0
feed U1
1
U1↷U2
2
post U2/T202
3
feed U1
4
U1⊘U2
5
feed U1
6
MapTimeline
#1→U1→T101
1/7
Narrationstep 1 of 7

User 1 posts tweet 101 at t=1.

1class Twitter:
2 def __init__(self):
3 self.time = 0
4 self.tweets = collections.defaultdict(list)
5 self.follows = collections.defaultdict(set)
6 def postTweet(self, u, t):
7 self.tweets[u].append((self.time, t)); self.time += 1
8 def getNewsFeed(self, u):
9 srcs = self.follows[u] | {u}
10 heap = []
11 for s in srcs:
12 for item in self.tweets[s]:
13 heapq.heappush(heap, (-item[0], item[1]))
14 return [heapq.heappop(heap)[1] for _ in range(min(10, len(heap)))]
15 def follow(self, f, g): self.follows[f].add(g)
16 def unfollow(self, f, g): self.follows[f].discard(g)
Variables
user=1
tweet=101
t=1

How to think about it

  1. Monotonic timestamps give a total ordering across users without clock drift.
  2. Feed = multi-way merge across (self + followees) using a max-heap keyed by timestamp.
  3. Return at most 10 entries.

Edge cases to catch in interview

  • User follows themselves -> treated once.
  • Feed before any posts -> empty.

Examples

Example 1[5]
{"ops":[{"op":"post","user":1,"tweet":5},{"op":"feed","user":1}],"values":["post U1/T5","feed U1"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed