medium +25 pts

Design Twitter Feed

Implement a Twitter-style feed with follow, unfollow, post, and chronological retrieval.

Design a simplified version of Twitter where users can post tweets, follow/unfollow other users, and see the 10 most recent tweets in their news feed. Implement a class `Twitter` with the following methods: - `__init__(self)` – initializes the Twitter object. - `postTweet(self, userId: int, tweetId: int) -> None` – posts a tweet with the given `tweetId` from the user `userId`. Each tweet has a unique `tweetId`, and each post increments the global timestamp by 1. - `getNewsFeed(self, userId: int) -> list` – retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by the user themself or by users the user follows. Tweets must be ordered from most recent to least recent. The timestamp is global and increases by 1 for each `postTweet` call. - `follow(self, followerId: int, followeeId: int) -> None` – the user with `followerId` starts following the user with `followeeId`. - `unfollow(self, followerId: int, followeeId: int) -> None` – the user with `followerId` stops following the user with `followeeId`. You must implement the class exactly with these method signatures. The test harness will call the methods directly on a `Twitter` instance.

Constraints

- 1 <= userId, followeeId, followerId <= 500 - 0 <= tweetId <= 10^4 - At most 10^4 calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow` combined. - A user cannot follow themselves. - `getNewsFeed` must return at most 10 tweets in most-recent-first order. - The global timestamp increases by 1 on each `postTweet` call. - `follow` is never called with followerId == followeeId.

Example

>>> twitter = Twitter()
>>> twitter.postTweet(1, 5)
>>> twitter.getNewsFeed(1)
[5]
>>> twitter.follow(1, 2)
>>> twitter.postTweet(2, 6)
>>> twitter.getNewsFeed(1)
[6, 5]
>>> twitter.unfollow(1, 2)
>>> twitter.getNewsFeed(1)
[5]
25 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a global counter for timestamps that increments each time a tweet is posted.
Store tweets per user in a list of (timestamp, tweetId) tuples.
For getNewsFeed, gather tweets from the user and all their followees, sort by timestamp descending, and take the first 10.
Use a set to store followees for each user to avoid duplicates.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.