1. Global Tweet Log Filtering
Intuition
Store all tweets globally in a single list [(timestamp, userId, tweetId)].
Maintain a follower mapping followers[followerId] = set of followeeIds.
When getNewsFeed(userId) is called, scan through the global tweet log backwards, checking if the author is userId or in the user's follow set.
Collect up to 10 tweets and return.
While simple, iterating through all global tweets scales with O(T) where T is the total number of tweets across all users.
When to apply: Toy models or small mock services.
Algorithm
- Step 1: Maintain a global tweets array and a followees map of sets.
- Step 2: On postTweet, append (timestamp++, userId, tweetId) to the global tweets array.
- Step 3: On follow and unfollow, add/remove followeeId from following[followerId].
- Step 4: On getNewsFeed, scan backwards from the end of global tweets, appending matching tweetIds until 10 are collected.
- Step 5: Return the collected list of tweet IDs.
#include <iostream>#include <vector>#include <unordered_map>#include <unordered_set> struct Tweet { int time; int userId; int tweetId;}; class TwitterBrute { int timer = 0; std::vector<Tweet> allTweets; std::unordered_map<int, std::unordered_set<int>> following;public: TwitterBrute() {} void postTweet(int userId, int tweetId) { allTweets.push_back({timer++, userId, tweetId}); } std::vector<int> getNewsFeed(int userId) { std::vector<int> feed; const auto& follows = following[userId]; for (int i = (int)allTweets.size() - 1; i >= 0 && feed.size() < 10; --i) { int author = allTweets[i].userId; if (author == userId || follows.count(author)) { feed.push_back(allTweets[i].tweetId); } } return feed; } void follow(int followerId, int followeeId) { if (followerId != followeeId) { following[followerId].insert(followeeId); } } void unfollow(int followerId, int followeeId) { following[followerId].erase(followeeId); }}; int main() { TwitterBrute twitter; twitter.postTweet(1, 5); auto f1 = twitter.getNewsFeed(1); std::cout << f1[0] << std::endl; twitter.follow(1, 2); twitter.postTweet(2, 6); auto f2 = twitter.getNewsFeed(1); for (int t : f2) std::cout << t << " "; std::cout << std::endl; twitter.unfollow(1, 2); auto f3 = twitter.getNewsFeed(1); for (int t : f3) std::cout << t << " "; std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(1) for postTweet, follow, unfollow; O(T) for getNewsFeed where T is total tweets - Space complexity:
O(T + U^2) where T is total tweets and U is number of users