MediumHash TableLinked ListDesignHeap (Priority Queue)

1 approach, code in every language

Problem description

Design a simplified version of Twitter where users can post tweets, follow and unfollow other users, and pull a personalized feed of the newest tweets from themselves and the people they follow.

Implement the class Twitter. postTweet(userId, tweetId) publishes a new tweet by the given user. getNewsFeed(userId) returns the ids of the ten most recent tweets in the user's feed, ordered from most recent to least recent, where the feed contains tweets posted by the user and by everyone the user follows. follow(followerId, followeeId) makes the follower start following the followee. unfollow(followerId, followeeId) makes the follower stop following the followee.

A user does not follow themselves, and following someone twice or unfollowing someone you do not follow has no effect.

Example 1

Input: operations = ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] args = [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

Output: [null, null, [5], null, null, [6, 5], null, [5]]

User 1 posts tweet 5, so the feed is [5]. User 1 follows user 2, who posts tweet 6, so the feed becomes [6, 5] with the newest first. After user 1 unfollows user 2, the feed returns to [5].

Example 2

Input: operations = ["Twitter", "postTweet", "postTweet", "getNewsFeed"] args = [[], [1, 101], [1, 102], [1]]

Output: [null, null, null, [102, 101]]

User 1 posts tweet 101 then tweet 102. The feed lists them newest first as [102, 101].

Constraints

  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10^4 and all tweetId values are unique.
  • At most 3 * 10^4 total calls will be made to postTweet, getNewsFeed, follow, and unfollow.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free