</>

355. Design Twitter

Medium NeetCode 150
Heap / Priority Queue Time O(f + 10 log f) per getNewsFeed, f = followees Space O(total tweets + follow edges)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Heap / Priority Queue
Time
O(f + 10 log f) per getNewsFeed, f = followees
Space
O(total tweets + follow edges)

Standard Solution (C++)

SummaryImplement a tiny social feed supporting posting tweets, following/unfollowing users, and fetching the 10 most recent tweets from a user and the people they follow.

Approach

Per-user tweet lists with a global timestamp, merged by a heap.

  • Each tweet is stored with a monotonically increasing global counter so ordering across users is well defined.
  • getNewsFeed: gather the latest tweet from the user and each followee into a max-heap keyed by timestamp; repeatedly pop the newest and push that user's previous tweet, up to 10 times.
class Twitter {
    int timer = 0;
    unordered_map<int, vector<pair<int,int>>> tweets;   // user -> (time, tweetId)
    unordered_map<int, unordered_set<int>> following;   // user -> set of followees
public:
    Twitter() {}

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

    vector<int> getNewsFeed(int userId) {
        // max-heap entries: (time, tweetId, ownerId, index-in-owner-list)
        priority_queue<array<int,4>> pq;
        unordered_set<int> users = following[userId];
        users.insert(userId);
        for (int u : users) {
            auto& tw = tweets[u];
            if (!tw.empty()) {
                int idx = tw.size() - 1;
                pq.push({tw[idx].first, tw[idx].second, u, idx});
            }
        }
        vector<int> res;
        while (!pq.empty() && (int)res.size() < 10) {
            auto top = pq.top(); pq.pop();
            res.push_back(top[1]);
            int u = top[2], idx = top[3];
            if (idx > 0) {
                auto& tw = tweets[u];
                pq.push({tw[idx-1].first, tw[idx-1].second, u, idx-1});
            }
        }
        return res;
    }

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

    void unfollow(int followerId, int followeeId) {
        following[followerId].erase(followeeId);
    }
};
Time O(f + 10 log f) per getNewsFeed, f = followees Space O(total tweets + follow edges)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern