Implement a Followable Microblog Timeline
Design an in-memory microblog service with these operations:
post(user_id, tweet_id)
follow(follower_id, followee_id)
unfollow(follower_id, followee_id)
get_latest_tweets(user_id) -> list[tweet_id]
get_latest_tweets returns at most the ten most recent tweet IDs posted by the user or by accounts the user currently follows, ordered from newest to oldest.
Required Behavior
-
Each call to
post
receives a unique
tweet_id
and an implicit monotonically increasing sequence number.
-
Following an account already followed is a no-op.
-
Unfollowing an account not followed is a no-op.
-
A user always sees their own tweets; self-follow and self-unfollow must not change that rule.
-
Follow state at query time determines which accounts contribute tweets.
-
If fewer than ten visible tweets exist, return all of them.
-
The service is single-threaded for this exercise.
Example
post(1, 101)
post(2, 201)
follow(1, 2)
post(2, 202)
get_latest_tweets(1) -> [202, 201, 101]
unfollow(1, 2)
get_latest_tweets(1) -> [101]
Constraints
-
Up to 100000 operations.
-
User and tweet IDs are integers.
-
A single user may post many tweets and follow many accounts.
-
Store enough history to answer later queries; no deletion operation is required.
Hints
-
Keep each user's tweets in chronological order.
-
At query time, the desired result is the top ten values from several already sorted streams.
-
A heap can merge the newest item from each visible stream without scanning every historical tweet.
-
After taking one tweet from a user's stream, only that stream's next older tweet becomes a new candidate.
Discussion Extensions
-
Derive query complexity in terms of the number of followed users and the result limit.
-
When would a fan-out-on-write timeline be preferable?
-
How would tweet deletion or muted users affect cached timelines?