355. Design Twitter

  • 25.1%

https://leetcode.com/problems/design-twitter/#/description

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. Your design should support the following methods:

  1. postTweet(userId, tweetId): Compose a new tweet.
  2. getNewsFeed(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.
  3. follow(followerId, followeeId): Follower follows a followee.
  4. unfollow(followerId, followeeId): Follower unfollows a followee.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// 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.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

https://discuss.leetcode.com/topic/48253/72ms-c-solution

72ms C++ solution

Complexity: O(1) post/follow/unfollow, O(n + k log n) newsfeed for getting k tweets from n followed users, with the O(n) part coming from constructing the heap of followed users (see below), as correctly noted by @poligun.

Use std::vector to store tweets, std::unordered_set to store followed users, std::unordered_map to associate each user with their tweets and followed users.

Use a heap to merge most recent k tweets from followed users. std::make/push/pop_heap provide finer control than std::priority_queue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Twitter
{
struct Tweet
{
int time;
int id;
Tweet(int time, int id) : time(time), id(id) {}
};

std::unordered_map<int, std::vector<Tweet>> tweets; // [u] = array of tweets by u
std::unordered_map<int, std::unordered_set<int>> following; // [u] = array of users followed by u

int time;

public:
Twitter() : time(0) {}

void postTweet(int userId, int tweetId)
{
tweets[userId].emplace_back(time++, tweetId);
}

std::vector<int> getNewsFeed(int userId)
{
std::vector<std::pair<Tweet*, Tweet*>> h; // pair of pointers (begin, current)

for (auto& u: following[userId])
{
auto& t = tweets[u];
if (t.size() > 0)
h.emplace_back(t.data(), t.data() + t.size() - 1);
}
auto& t = tweets[userId]; // self
if (t.size() > 0)
h.emplace_back(t.data(), t.data() + t.size() - 1);

auto f = [](const std::pair<Tweet*, Tweet*>& x, const std::pair<Tweet*, Tweet*>& y) {
return x.second->time < y.second->time;
};
std::make_heap(h.begin(), h.end(), f);

const int n = 10;
std::vector<int> o;
o.reserve(n);
for (int i = 0; (i < n) && !h.empty(); ++i)
{
std::pop_heap(h.begin(), h.end(), f);

auto& hb = h.back();
o.push_back(hb.second->id);

if (hb.first == hb.second--)
h.pop_back();
else
std::push_heap(h.begin(), h.end(), f);
}
return o;
}

void follow(int followerId, int followeeId)
{
if (followerId != followeeId)
following[followerId].insert(followeeId);
}

void unfollow(int followerId, int followeeId)
{
following[followerId].erase(followeeId);
}
};

https://discuss.leetcode.com/topic/47922/c-80ms-unordered_map-list-priority_queue-solution

C++ 80ms unordered_map list priority_queue solution

Time Complexity: n is number of user

postTweet: O(1)

getNewsFeed: O(n log n)

follow: O(1)

unfollow: O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Twitter {
private:
struct tweet{
int userId;
int tweetId;
int timestamp;
tweet(int x, int y, int z):userId(x), tweetId(y), timestamp(z){};
};
struct mycompare{
bool operator()(pair<list<tweet>::iterator, list<tweet>::iterator> p1, pair<list<tweet>::iterator, list<tweet>::iterator> p2){
return p1.first->timestamp < p2.first->timestamp;
}
};
int timelabel = 0;
unordered_map<int, unordered_set<int>> follower_dict;
unordered_map<int, list<tweet>> twitter_dict;
public:
/** Initialize your data structure here. */
Twitter() {}

/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
follower_dict[userId].insert(userId);
twitter_dict[userId].push_front(tweet(userId, tweetId, timelabel));
timelabel++;
}

/** 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. */
vector<int> getNewsFeed(int userId) {
vector<int> res;
if(follower_dict.find(userId) == follower_dict.end()) return res;
priority_queue< pair<list<tweet>::iterator, list<tweet>::iterator>, vector<pair<list<tweet>::iterator, list<tweet>::iterator>>, mycompare> pq;
for(auto it = follower_dict[userId].begin(); it != follower_dict[userId].end(); it++){
if(twitter_dict[*it].begin() != twitter_dict[*it].end()){
pq.push(make_pair(twitter_dict[*it].begin(), twitter_dict[*it].end()));
}
}
int index = 0;
while(!pq.empty() && index < 10){
auto tmp = pq.top();
pq.pop();
res.push_back(tmp.first->tweetId);
if(++tmp.first != tmp.second){
pq.push(tmp);
}
index++;
}
return res;
}

/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
void follow(int followerId, int followeeId) {
follower_dict[followerId].insert(followerId);
follower_dict[followerId].insert(followeeId);
}

/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
void unfollow(int followerId, int followeeId) {
if(follower_dict.find(followerId) != follower_dict.end() && followerId != followeeId){
follower_dict[followerId].erase(followeeId);
}
}
};

https://discuss.leetcode.com/topic/47838/python-solution

Python solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Twitter(object):

def __init__(self):
self.timer = itertools.count(step=-1)
self.tweets = collections.defaultdict(collections.deque)
self.followees = collections.defaultdict(set)

def postTweet(self, userId, tweetId):
self.tweets[userId].appendleft((next(self.timer), tweetId))

def getNewsFeed(self, userId):
tweets = heapq.merge(*(self.tweets[u] for u in self.followees[userId] | {userId}))
return [t for _, t in itertools.islice(tweets, 10)]

def follow(self, followerId, followeeId):
self.followees[followerId].add(followeeId)

def unfollow(self, followerId, followeeId):
self.followees[followerId].discard(followeeId)

https://discuss.leetcode.com/topic/48166/simple-and-clean-python-code-o-logk-for-getting-news-feed

Simple and Clean Python code, O(logK) for getting news feed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import heapq

class Twitter(object):

def __init__(self):
self.time = 0
self.tweets = {}
self.followee = {}


def postTweet(self, user, tweet):
self.time += 1
self.tweets[user] = self.tweets.get(user, []) + [(-self.time, tweet)]



def getNewsFeed(self, user):
h, tweets = [], self.tweets
people = self.followee.get(user, set()) | set([user])
for person in people:
if person in tweets and tweets[person]:
time, tweet = tweets[person][-1]
h.append((time, tweet, person, len(tweets[person]) - 1))
heapq.heapify(h)
news = []
for _ in range(10):
if h:
time, tweet, person, idx = heapq.heappop(h)
news.append(tweet)
if idx:
new_time, new_tweet = tweets[person][idx-1]
heapq.heappush(h, (new_time, new_tweet, person, idx - 1))
return news



def follow(self, follower, other):
self.followee[follower] = self.followee.get(follower, set()) | set([other])



def unfollow(self, follower, other):
if follower in self.followee:
self.followee[follower].discard(other)

K is the number of followee of user. We have O(log(K)) runtime for getting news feed because we do maximum 10 extractions in a heap that holds maximum K elements (similar to what is done in merge K linked lists). The other ops are obviously O(1).


java

175ms, 50.30%, September 22, 2016

https://discuss.leetcode.com/topic/48100/java-oo-design-with-most-efficient-function-getnewsfeed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
public class Twitter {
private static int timeStamp = 0;
private Map<Integer, User> userMap;
private class Tweet{
public int id;
public int time;
public Tweet next;

public Tweet(int id){
this.id = id;
time = timeStamp++;
next = null;
}
}

public class User{
public int id;
public Set<Integer> followed;
public Tweet tweet_head;

public User(int id){
this.id = id;
followed = new HashSet<>();
follow(id);
tweet_head = null;
}

public void follow(int id){
followed.add(id);
}

public void unfollow(int id){
followed.remove(id);
}

public void post(int id){
Tweet t = new Tweet(id);
t.next = tweet_head;
tweet_head = t;
}
}


/** Initialize your data structure here. */
public Twitter() {
userMap = new HashMap<Integer, User>();
}

/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
if(!userMap.containsKey(userId)){
User u = new User(userId);
userMap.put(userId, u);
}
userMap.get(userId).post(tweetId);
}

/** 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 List<Integer> getNewsFeed(int userId) {
List<Integer> res = new LinkedList<>();
if(!userMap.containsKey(userId)) return res;
Set<Integer> users = userMap.get(userId).followed;
PriorityQueue<Tweet> q = new PriorityQueue<Tweet>(users.size(), (a, b)->(b.time-a.time));
for(int user : users){
Tweet t = userMap.get(user).tweet_head;
if(t!=null)
q.add(t);
}
int n=0;
while(!q.isEmpty() && n < 10){
Tweet t = q.poll();
res.add(t.id);
n++;
if(t.next!=null)
q.add(t.next);
}
return res;
}

/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
public void follow(int followerId, int followeeId) {
if(!userMap.containsKey(followerId)){
User u = new User(followerId);
userMap.put(followerId, u);
}
if(!userMap.containsKey(followeeId)){
User u = new User(followeeId);
userMap.put(followeeId, u);
}
userMap.get(followerId).follow(followeeId);
}

/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
public void unfollow(int followerId, int followeeId) {
if(!userMap.containsKey(followerId) || followerId == followeeId)
return;
userMap.get(followerId).unfollow(followeeId);
}
}

/**
* Your Twitter object will be instantiated and called as such:
* Twitter obj = new Twitter();
* obj.postTweet(userId,tweetId);
* List<Integer> param_2 = obj.getNewsFeed(userId);
* obj.follow(followerId,followeeId);
* obj.unfollow(followerId,followeeId);
*/

python

109ms, 66.92%, September 22, 2016

https://discuss.leetcode.com/topic/47838/python-solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Twitter(object):

def __init__(self):
"""
Initialize your data structure here.
"""
self.timer = itertools.count(step=-1)
self.tweets = collections.defaultdict(collections.deque)
self.followees = collections.defaultdict(set)


def postTweet(self, userId, tweetId):
"""
Compose a new tweet.
:type userId: int
:type tweetId: int
:rtype: void
"""
self.tweets[userId].appendleft((next(self.timer), tweetId))


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]
"""
tweets = heapq.merge(*(self.tweets[u] for u in self.followees[userId] | {userId}))
return [t for _, t in itertools.islice(tweets, 10)]


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
"""
self.followees[followerId].add(followeeId)


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
"""
self.followees[followerId].discard(followeeId)



# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)
谢谢你,可爱的朋友。