Design Twitter Problem
Description
LeetCode Problem 355.
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed.
Implement the Twitter class:
- Twitter() Initializes your twitter object.
- void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.
- List getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.
- void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId.
- void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.
Example 1:
Input
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[null, null, [5], null, null, [6, 5], null, [5]]
Explanation
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]
twitter.follow(1, 2); // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2); // User 1 unfollows user 2.
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
Constraints:
- 1 <= userId, followerId, followeeId <= 500
- 0 <= tweetId <= 10^4
- All the tweets have unique IDs.
- At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
Solution
Approach: Per-User Tweet Lists + Heap Merge
Store three things:
- a global
timecounter that goes up by one with every tweet, so a bigger time means a more recent tweet; - for each user, the list of their tweets
(time, tweetId)in the order they were posted (oldest first); - for each user, the set of users they follow.
postTweet appends to the user's list, and follow / unfollow add to or remove from the set. Both are O(1).
getNewsFeed has to merge several lists that are each sorted by time and keep only the 10 newest, the same as merging k sorted lists:
- The sources are everyone the user follows, plus the user themself.
- Push the newest tweet of each source into a max-heap ordered by time, together with its user and its index in that user's list.
- Pop the newest tweet into the feed, then push the next older tweet of the same user (index − 1). Stop after 10 tweets or when the heap is empty.
The user's own tweets must always be in the feed. Add the user to the sources when building the feed instead of storing a "self-follow" in the set: then a call like unfollow(3, 3) cannot hide user 3's own tweets.
Complexity: postTweet, follow and unfollow take O(1) time. getNewsFeed takes O(f log f) time, where f is the number of users followed: building the heap dominates, and the 10 pops cost O(log f) each. O(t + e) space for t tweets and e follow relations.
import collections
import heapq
class Twitter:
FEED_SIZE = 10
def __init__(self):
self.time = 0 # increases with every tweet
self.tweets = collections.defaultdict(list) # user -> [(time, tweetId)], oldest first
self.following = collections.defaultdict(set) # user -> users they follow
def postTweet(self, userId: int, tweetId: int) -> None:
self.tweets[userId].append((self.time, tweetId))
self.time += 1
def getNewsFeed(self, userId: int) -> List[int]:
sources = self.following[userId] | {userId} # a user always sees their own tweets
# Max-heap (by time) holding the newest not-yet-taken tweet of each source user.
heap = []
for user in sources:
if self.tweets[user]:
last = len(self.tweets[user]) - 1
heapq.heappush(heap, (-self.tweets[user][last][0], user, last))
feed = []
while heap and len(feed) < self.FEED_SIZE:
_, user, index = heapq.heappop(heap)
feed.append(self.tweets[user][index][1])
if index > 0: # this user's next older tweet
heapq.heappush(heap, (-self.tweets[user][index - 1][0], user, index - 1))
return feed
def follow(self, followerId: int, followeeId: int) -> None:
self.following[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
self.following[followerId].discard(followeeId)
Now write it from memory
Close the write-up and solve it yourself against the tests.