## Algorithm

Problem Name: 355. Design Twitter

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<Integer> 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.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 <= 104`
• All the tweets have unique IDs.
• At most `3 * 104` calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`.

## Code Examples

### #1 Code Example with C++ Programming

```Code - C++ Programming```

``````
private:
vector<pair<int,int>>posts;
unordered_map < int, unordered_map<int, int>>follows;
public:

void postTweet(int userId, int tweetId) {
posts.push_back(make_pair(userId, tweetId));
}

vector<int> getNewsFeed(int userId) {
vector<int>feed;
int count = 0;
for(int i = posts.size() - 1; i >= 0 && count  <  10; i--)
if(posts[i].first == userId || follows[userId][posts[i].first])
feed.push_back(posts[i].second), count++;
return feed;
}

void follow(int followerId, int followeeId) {
follows[followerId][followeeId] = 1;
}

void unfollow(int followerId, int followeeId) {
follows[followerId][followeeId] = 0;
}
};
``````
Copy The Code &

Input

cmd
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

Output

cmd
[null, null, [5], null, null, [6, 5], null, [5]]

### #2 Code Example with Java Programming

```Code - Java Programming```

``````
import java.util.Map.Entry;

private final Map < Integer, Set userToTweet;
private int timestamp;

this.userFollowing = new HashMap < >();
this.timestamp = 0;
this.userToTweet = new HashMap < >();
}

public void postTweet(int userId, int tweetId) {
TweetNode tweetNode = new TweetNode(tweetId, this.timestamp++);
if (this.userToTweet.containsKey(userId)) {
tweetNode.next = this.userToTweet.get(userId);
}
this.userToTweet.put(userId, tweetNode);
}

public List < Integer> getNewsFeed(int userId) {
PriorityQueue priorityQueue =
new PriorityQueue<>((o1, o2) -> o2.timestamp - o1.timestamp);
this.userToTweet.entrySet().stream()
.filter(
entry ->
entry.getKey() == userId
|| this.userFollowing
.getOrDefault(userId, new HashSet<>())
.contains(entry.getKey()))
.map(Entry::getValue)
.collect(Collectors.toList()));
List < Integer> result = new ArrayList<>();
while (!priorityQueue.isEmpty() && result.size() < 10) {
TweetNode removed = priorityQueue.remove();
if (removed.next != null) {
}
}
return result;
}

public void follow(int followerId, int followeeId) {
this.userFollowing.computeIfAbsent(followerId, k -> new HashSet < >()).add(followeeId);
}

public void unfollow(int followerId, int followeeId) {
if (this.userFollowing.getOrDefault(followerId, new HashSet<>()).contains(followeeId)) {
this.userFollowing.get(followerId).remove(followeeId);
}
}

private static class TweetNode {
int tweetId;
int timestamp;
TweetNode next;

public TweetNode(int tweetId, int timestamp) {
this.tweetId = tweetId;
this.timestamp = timestamp;
}
}
}
``````
Copy The Code &

Input

cmd
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

Output

cmd
[null, null, [5], null, null, [6, 5], null, [5]]

### #3 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
const Twitter = function() {
this.userTweets = new Map()
this.userFollowing = new Map()
this.lastIndex = 1
}

Twitter.prototype.postTweet = function(userId, tweetId) {
let tweets = this.userTweets.get(userId)
if (!tweets) {
tweets = []
this.userTweets.set(userId, tweets)
}
tweets.unshift({ id: tweetId, index: this.lastIndex })
this.lastIndex = this.lastIndex + 1
}

Twitter.prototype.getNewsFeed = function(userId) {
const followings = this.userFollowing.get(userId)
let tweets = (this.userTweets.get(userId) || []).slice(0, 10)
followings &&
followings.forEach(uid => {
if (uid === userId) return

const userTweets = this.userTweets.get(uid)
if (userTweets) {
tweets = tweets.concat(userTweets)
}
})
return tweets
.sort((a, b) => b.index - a.index)
.map(tweet => tweet.id)
.slice(0, 10)
}

let followings = this.userFollowing.get(followerId)
if (!followings) {
followings = new Set()
this.userFollowing.set(followerId, followings)
}
}

const followings = this.userFollowing.get(followerId)
followings && followings.delete(followeeId)
}
``````
Copy The Code &

Input

cmd
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

Output

cmd
[null, null, [5], null, null, [6, 5], null, [5]]

### #4 Code Example with Python Programming

```Code - Python Programming```

``````

def __init__(self):
"""
Initialize your data structure here.
"""
self.tweets = collections.defaultdict(list)
self.following = collections.defaultdict(set)
self.order = 0
def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.tweets[userId] += (self.order, tweetId),
self.order -= 1

def getNewsFeed(self, userId):
"""
Retrieve 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 herself. Tweets must be ordered from most recent to least recent.
:type userId: int
:rtype: List[int]
"""
tw = sorted(tw for i in self.following[userId] | {userId} for tw in self.tweets[i])[:10]
return [news for i, news in tw]

def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""

def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
:type followerId: int
:type followeeId: int
:rtype: void
"""
``````
Copy The Code &

Input

cmd
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

Output

cmd
[null, null, [5], null, null, [6, 5], null, [5]]

### #5 Code Example with C# Programming

```Code - C# Programming```

``````
using System.Collections.Generic;
using System.Linq;

namespace LeetCode
{
{
private readonly Dictionary < int, User> users;
private int timestamp = 0;

/** Initialize your data structure here. */
{
users = new Dictionary < int, User>();
}

/** Compose a new tweet. */
public void PostTweet(int userId, int tweetId)
{
if (!users.ContainsKey(userId))
users[userId] = new User(userId);
users[userId].post(tweetId, timestamp++);
}

/** Retrieve 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 herself. Tweets must be ordered from most recent to least recent. */
public IList < int> GetNewsFeed(int userId)
{
if (!users.ContainsKey(userId))
{
users[userId] = new User(userId);
return new List<int>();
}

var followers = new HashSet < int>(users[userId].Followed);
var tweets = new SortedDictionary < Tweet, int>(Comparer.Create((a, b) => b.Time.CompareTo(a.Time)));
foreach (var id in followers)
{
if (users[id].TweetHead != null)
}

var count = 10;
var results = new List < int>();
while (tweets.Count > 0 && count > 0)
{
var t = tweets.Keys.First();
tweets.Remove(t);

if (t.Next != null)

count--;
}

return results;
}

public void Follow(int followerId, int followeeId)
{
if (followerId == followeeId) return;

if (!users.ContainsKey(followerId))
users[followerId] = new User(followerId);
if (!users.ContainsKey(followeeId))
users[followeeId] = new User(followeeId);

users[followerId].Follow(followeeId);
}

public void Unfollow(int followerId, int followeeId)
{
if (!users.ContainsKey(followerId))
users[followerId] = new User(followerId);
if (!users.ContainsKey(followeeId))
users[followeeId] = new User(followeeId);

users[followerId].Unfollow(followeeId);
}

public class Tweet
{
public Tweet(int id, int timestamp)
{
Id = id;
Time = timestamp;
Next = null;
}

public int Id { get; private set; }
public int Time { get; private set; }
public Tweet Next { get; set; }
}

public class User
{
public int Id { get; private set; }
public HashSet < int> Followed { get; } = new HashSet<int>();
public Tweet TweetHead { get; private set; }

public User(int id)
{
Id = id;
}

public void Follow(int id)
{
}

public void Unfollow(int id)
{
Followed.Remove(id);
}

// everytime user post a new tweet, add it to the head of tweet list.
public void post(int id, int timestamp)
{
Tweet newTweet = new Tweet(id, timestamp);
}
}
}

}
``````
Copy The Code &

Input

cmd
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

Output

cmd
[null, null, [5], null, null, [6, 5], null, [5]]