Top 150 Interview簡単

Design Twitter

Detailed guide and Python implementation for the 'Design Twitter' problem.

問題提起

簡単

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.

- postTweet(userId: int, tweetId: int) Composes a new tweet with ID tweetId by the user userId.

- getNewsFeed(userId: int) -> List[int] Retrieves the 10 most recent tweet IDs in the user's news feed.

- follow(followerId: int, followeeId: int) The user with ID followerId started following the user with ID followeeId.

- unfollow(followerId: int, followeeId: int) The user with ID followerId started unfollowing the user with ID followeeId.

Input is a list of operations and arguments. Implement a function twitter(operations: list, arguments: list) -> list that returns a list of results (None for constructor/postTweet/follow/unfollow, and List[int] for getNewsFeed).

制約
  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10^4
  • All the tweets have unique IDs
  • At most 30000 calls will be made in total

Example 1
Input
operations = ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"], arguments = [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[None, None, [5], None, None, [6, 5], None, [5]]
Explanation

User 1 posts tweet 5. News feed: [5]. User 1 follows 2. User 2 posts tweet 6. News feed: [6, 5]. User 1 unfollows 2. News feed: [5].

Need a Hint?
Consider using Heap / Priority Queue-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。