DSA interview question
Build a tiny version of Twitter. Users can postTweet(userId, tweetId), follow(followerId, followeeId) and unfollow(...), and getNewsFeed(userId) returns the 10 most recent tweet IDs posted by the user or anyone they follow, newest first. Each user's own tweets are stored in time order, so a news feed is a k-way merge of already-sorted lists (the user plus their followees). A max-heap keyed by timestamp pulls the 10 newest without touching older tweets.
Example: postTweet(1, 5); getNewsFeed(1) → [5]; follow(1, 2); postTweet(2, 6); getNewsFeed(1) → [6, 5]; unfollow(1, 2); getNewsFeed(1) → [5].
class Twitter {
public:
void postTweet(int userId, int tweetId);
vector<int> getNewsFeed(int userId); // up to 10 tweet ids, newest first
void follow(int followerId, int followeeId);
void unfollow(int followerId, int followeeId);
};
| Operations | Output | Explanation |
|---|---|---|
post(1,5) feed(1) follow(1,2) post(2,6) feed(1) unfollow(1,2) feed(1) | [5] [6, 5] [5] | LeetCode's example |
user 1 posts tweets 1 to 11, then feed(1) | [11, 10, 9, 8, 7, 6, 5, 4, 3, 2] | Only the 10 newest |
follow(1,1) post(1,7) feed(1) | [7] | Following yourself must not duplicate |
post(2,3) follow(1,2) post(1,4) post(2,8) feed(1) | [8, 4, 3] | Interleaved by time |
feed(9) for a user with nothing | [] |
(Confirm: "recent" means posting order across all users; unfollowing someone you don't follow is a no-op; users always see their own tweets.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in