forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0355-design-twitter.java
270 lines (213 loc) · 7.24 KB
/
0355-design-twitter.java
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
class User {
private int uid;
private Set<Integer> followingIDs;
private List<Integer> tweetIDs;
public User(int uid) {
this.uid = uid;
this.followingIDs = new HashSet<>();
this.followingIDs.add(this.uid); // by default, follows self
this.tweetIDs = new ArrayList<>();
}
public Set<Integer> getFollowingIDs() {
return this.followingIDs;
}
public List<Integer> getTweetIDs() {
return this.tweetIDs;
}
public int getID() {
return this.uid;
}
@Override
public String toString() {
return (
"[" +
this.uid +
", following: " +
this.followingIDs +
", tweets: " +
this.tweetIDs +
"]"
);
}
// Most recent ones are at the end
public void follow(int fid) {
this.followingIDs.add(fid);
}
public void unfollow(int fid) {
this.followingIDs.remove(fid);
}
// If remove tweet existed, treeSet would've been used (to maintain ordering)
public void postTweet(int tweetID) {
this.tweetIDs.add(tweetID);
}
}
class Tweet {
private int tweetID;
private int timestamp;
public Tweet(int tweetID, int timestamp) {
this.tweetID = tweetID;
this.timestamp = timestamp;
}
public int getTimeStamp() {
return this.timestamp;
}
public Integer getTweetID() {
return this.tweetID;
}
@Override
public String toString() {
return "{" + this.tweetID + "," + this.timestamp + "}";
}
}
class Database {
private static int GLOBAL_TIME = 0;
// 1 <= userID <= 500 ---> Can be 501 sized array instead of HashMap
private static int NUM_USERS = 501;
private User[] users;
private boolean[] userExists;
// 0 <= tweetID <= 10^4 --> Can be 10^4 + 1 sized array instead of HashMap
private static int NUM_TWEETS = 10000 + 1;
private Tweet[] tweets;
// Acts like a 'node' to indicate where to go next
class Triplet {
int userId;
int index;
int tweetID;
public Triplet(int userId, int index, int tweetID) {
this.userId = userId;
this.index = index;
this.tweetID = tweetID;
}
@Override
public String toString() {
return (
"[" + this.userId + "," + this.index + "," + this.tweetID + "]"
);
}
}
// Compare the linked list of tweets present in the user class
// Nested class to access the 'tweets'
class TweetComparator implements Comparator<Triplet> {
@Override
public int compare(Triplet o1, Triplet o2) {
// Compare max. with respect to timestamp
return (
tweets[o2.tweetID].getTimeStamp() -
tweets[o1.tweetID].getTimeStamp()
);
}
}
// From outside, Database.TweetComparator obj = databaseObj.new TweetComparator()
private TweetComparator comparator;
// Constructor
public Database() {
this.users = new User[NUM_USERS];
this.userExists = new boolean[NUM_USERS];
Arrays.fill(this.userExists, false);
this.tweets = new Tweet[NUM_TWEETS];
this.comparator = new TweetComparator();
}
private void createUserMaybe(int uid) {
if (this.userExists[uid]) return;
this.userExists[uid] = true;
User user = new User(uid);
this.users[uid] = user;
}
private void createTweet(int tweetId) {
Tweet tweet = new Tweet(tweetId, Database.GLOBAL_TIME);
Database.GLOBAL_TIME++;
this.tweets[tweetId] = tweet;
}
public void postTweet(int uid, int tweetId) {
// Create new User if doesn't exist
createUserMaybe(uid);
// Create new Tweet
createTweet(tweetId);
// Post the tweet
this.users[uid].postTweet(tweetId);
}
public void follow(int followerId, int followeeId) {
// Create users if doesn't exist
createUserMaybe(followerId);
createUserMaybe(followeeId);
// Follow
this.users[followerId].follow(followeeId);
}
public void unfollow(int followerId, int followeeId) {
// Create users if doesn't exist
createUserMaybe(followerId);
createUserMaybe(followeeId);
// Unfollow
this.users[followerId].unfollow(followeeId);
}
private List<Tweet> getMaxTopK(int userId, int k) {
// Check if this user exists or not
if (!this.userExists[userId]) return new ArrayList<>();
// Use top k of sorted list type logic
PriorityQueue<Triplet> pq = new PriorityQueue<>(this.comparator);
User user = this.users[userId];
Set<Integer> followingIDs = user.getFollowingIDs();
// Take the most recent (i.e. last) tweet for each of the following user
for (int followingID : followingIDs) {
User followingUser = this.users[followingID];
List<Integer> followingUserTweetIds = followingUser.getTweetIDs();
if (followingUserTweetIds.isEmpty()) continue;
int lastIndex = followingUserTweetIds.size() - 1;
int mostRecentTweetID = followingUserTweetIds.get(lastIndex);
Triplet triplet = new Triplet(
followingID,
lastIndex,
mostRecentTweetID
);
pq.add(triplet);
}
// Now, remove from pq, and "move required pointers/links" accordingly
List<Tweet> maxTweets = new ArrayList<>();
while (!pq.isEmpty() && (maxTweets.size() < k)) {
Triplet top = pq.remove();
maxTweets.add(tweets[top.tweetID]);
// For this top's user, if 'lesser' recent tweet is available, add to pq
int userID = top.userId;
int nextIndex = top.index - 1; // move backwards due to ArrayList
if (nextIndex < 0) continue;
int newTweetID = users[userID].getTweetIDs().get(nextIndex);
Triplet newTriplet = new Triplet(userID, nextIndex, newTweetID);
pq.add(newTriplet);
}
return maxTweets;
}
public List<Integer> getMaxTop10TweetIDs(int userId) {
List<Tweet> tweets = getMaxTopK(userId, 10);
// Instead of streams, normal for loop may also be used
return tweets
.stream()
.map(x -> x.getTweetID())
.collect(Collectors.toList());
}
}
class Twitter {
private Database db;
public Twitter() {
this.db = new Database();
}
public void postTweet(int userId, int tweetId) {
this.db.postTweet(userId, tweetId);
}
public List<Integer> getNewsFeed(int userId) {
return db.getMaxTop10TweetIDs(userId);
}
public void follow(int followerId, int followeeId) {
this.db.follow(followerId, followeeId);
}
public void unfollow(int followerId, int followeeId) {
this.db.unfollow(followerId, 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);
*/