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.
  • 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.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
**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 twitter = new Twitter();
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 <= 10^4
  • All the tweets have unique IDs.
  • At most 3 * 10^4 calls will be made to postTweetgetNewsFeedfollow, and unfollow.

Solution

Method 1 - Using Hashmap for Users, Set for Followers and Maxheap for Newsfeed

Intuition

The main idea is to use a combination of a HashMap and a Linked List to efficiently manage users, their tweets, and the follow relationships. The HashMap allows for O(1) access to user objects, while the Linked List enables quick insertion of new tweets at the head, ensuring the most recent tweets are always accessible. This structure is particularly effective for retrieving the latest tweets for a user’s news feed.

Approach

  1. User Management: Maintain a HashMap mapping user IDs to User objects. Each User object keeps track of the users they follow and their own tweets.
  2. Posting Tweets: When a user posts a tweet, create a new Tweet node and insert it at the head of the user’s tweet linked list. This ensures the most recent tweet is always at the front.
  3. Following/Unfollowing: Update the followed set in the User object to add or remove followees.
  4. News Feed Retrieval:
    • For a given user, collect the tweet heads of all users they follow (including themselves).
    • Use a max-heap (priority queue) to always retrieve the most recent tweet among all followed users.
    • Pop up to 10 tweets from the heap to form the news feed, always pushing the next tweet from the same user if available.

Complexity

  • ⏰ Time complexity: O(N log k) for news feed retrieval, where N is the total number of tweets and k is the number of followed users. Each tweet insertion and heap operation is efficient due to the data structures used.
  • 🧺 Space complexity: O(N + U + F), where N is the number of tweets, U is the number of users, and F is the number of follow relationships. Each tweet and user is stored, and the heap for feed retrieval uses extra space.

Code

 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
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); // follow self
            tweet_head = null;
        }
        public void follow(int id) {
            followed.add(id);
        }
        public void unfollow(int id) {
            if (id != this.id) followed.remove(id);
        }
        public void post(int id) {
            Tweet t = new Tweet(id);
            t.next = tweet_head;
            tweet_head = t;
        }
    }

    public Twitter() {
        userMap = new HashMap<>();
    }

    public void postTweet(int userId, int tweetId) {
        userMap.putIfAbsent(userId, new User(userId));
        userMap.get(userId).post(tweetId);
    }

    public void follow(int followerId, int followeeId) {
        userMap.putIfAbsent(followerId, new User(followerId));
        userMap.putIfAbsent(followeeId, new User(followeeId));
        userMap.get(followerId).follow(followeeId);
    }

    public void unfollow(int followerId, int followeeId) {
        if (userMap.containsKey(followerId)) {
            userMap.get(followerId).unfollow(followeeId);
        }
    }

    public List<Integer> getNewsFeed(int userId) {
        List<Integer> ans = new ArrayList<>();
        if (!userMap.containsKey(userId)) return ans;
        Set<Integer> users = userMap.get(userId).followed;
        PriorityQueue<Tweet> heap = new PriorityQueue<>((a, b) -> b.time - a.time);
        for (int uid : users) {
            Tweet t = userMap.get(uid).tweet_head;
            if (t != null) heap.offer(t);
        }
        int n = 0;
        while (!heap.isEmpty() && n < 10) {
            Tweet t = heap.poll();
            ans.add(t.id);
            n++;
            if (t.next != null) heap.offer(t.next);
        }
        return ans;
    }
}
 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
class Twitter {
    struct Tweet {
        int id, time;
        Tweet* next;
        Tweet(int id, int time) : id(id), time(time), next(nullptr) {}
    };
    struct User {
        int id;
        unordered_set<int> followed;
        Tweet* tweet_head;
        User(int id) : id(id), tweet_head(nullptr) {
            followed.insert(id);
        }
        void follow(int uid) { followed.insert(uid); }
        void unfollow(int uid) { if (uid != id) followed.erase(uid); }
        void post(int tid, int time) {
            Tweet* t = new Tweet(tid, time);
            t->next = tweet_head;
            tweet_head = t;
        }
    };
    unordered_map<int, User*> userMap;
    int timeStamp = 0;
public:
    Twitter() {}
    void postTweet(int userId, int tweetId) {
        if (!userMap.count(userId)) userMap[userId] = new User(userId);
        userMap[userId]->post(tweetId, timeStamp++);
    }
    void follow(int followerId, int followeeId) {
        if (!userMap.count(followerId)) userMap[followerId] = new User(followerId);
        if (!userMap.count(followeeId)) userMap[followeeId] = new User(followeeId);
        userMap[followerId]->follow(followeeId);
    }
    void unfollow(int followerId, int followeeId) {
        if (userMap.count(followerId)) userMap[followerId]->unfollow(followeeId);
    }
    vector<int> getNewsFeed(int userId) {
        vector<int> ans;
        if (!userMap.count(userId)) return ans;
        auto& users = userMap[userId]->followed;
        auto cmp = [](Tweet* a, Tweet* b) { return a->time < b->time; };
        priority_queue<Tweet*, vector<Tweet*>, decltype(cmp)> heap(cmp);
        for (int uid : users) {
            Tweet* t = userMap[uid]->tweet_head;
            if (t) heap.push(t);
        }
        int n = 0;
        while (!heap.empty() && n < 10) {
            Tweet* t = heap.top(); heap.pop();
            ans.push_back(t->id);
            n++;
            if (t->next) heap.push(t->next);
        }
        return ans;
    }
};
 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 Tweet:
    def __init__(self, tid: int, time: int):
        self.id = tid
        self.time = time
        self.next: 'Tweet|None' = None

class User:
    def __init__(self, uid: int):
        self.id = uid
        self.followed = set([uid])
        self.tweet_head: Tweet|None = None
    def follow(self, uid: int):
        self.followed.add(uid)
    def unfollow(self, uid: int):
        if uid != self.id:
            self.followed.discard(uid)
    def post(self, tid: int, time: int):
        t = Tweet(tid, time)
        t.next = self.tweet_head
        self.tweet_head = t

class Twitter:
    def __init__(self):
        self.timeStamp = 0
        self.userMap: dict[int, User] = {}
    def postTweet(self, userId: int, tweetId: int) -> None:
        if userId not in self.userMap:
            self.userMap[userId] = User(userId)
        self.userMap[userId].post(tweetId, self.timeStamp)
        self.timeStamp += 1
    def follow(self, followerId: int, followeeId: int) -> None:
        if followerId not in self.userMap:
            self.userMap[followerId] = User(followerId)
        if followeeId not in self.userMap:
            self.userMap[followeeId] = User(followeeId)
        self.userMap[followerId].follow(followeeId)
    def unfollow(self, followerId: int, followeeId: int) -> None:
        if followerId in self.userMap:
            self.userMap[followerId].unfollow(followeeId)
    def getNewsFeed(self, userId: int) -> list[int]:
        ans: list[int] = []
        if userId not in self.userMap:
            return ans
        users = self.userMap[userId].followed
        import heapq
        heap = []
        for uid in users:
            t = self.userMap[uid].tweet_head
            if t:
                heapq.heappush(heap, (-t.time, t))
        n = 0
        while heap and n < 10:
            _, t = heapq.heappop(heap)
            ans.append(t.id)
            n += 1
            if t.next:
                heapq.heappush(heap, (-t.next.time, t.next))
        return ans