Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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.Example 1:
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 <= 5000 <= tweetId <= 1043 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Linked List · Design
["Twitter","postTweet","getNewsFeed","follow","postTweet","getNewsFeed","unfollow","getNewsFeed"] [[],[1,5],[1],[1,2],[2,6],[1],[1,2],[1]]
design-a-file-sharing-system)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #355: Design Twitter
class Twitter {
private Map<Integer, List<Integer>> userTweets;
private Map<Integer, Set<Integer>> userFollowing;
private Map<Integer, Integer> tweets;
private int time;
/** Initialize your data structure here. */
public Twitter() {
userTweets = new HashMap<>();
userFollowing = new HashMap<>();
tweets = new HashMap<>();
time = 0;
}
/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
userTweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(tweetId);
tweets.put(tweetId, ++time);
}
/**
* Retrieve 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 herself. Tweets must be ordered
* from most recent to least recent.
*/
public List<Integer> getNewsFeed(int userId) {
Set<Integer> following = userFollowing.getOrDefault(userId, new HashSet<>());
Set<Integer> users = new HashSet<>(following);
users.add(userId);
PriorityQueue<Integer> pq
= new PriorityQueue<>(10, (a, b) -> (tweets.get(b) - tweets.get(a)));
for (Integer u : users) {
List<Integer> userTweet = userTweets.get(u);
if (userTweet != null && !userTweet.isEmpty()) {
for (int i = userTweet.size() - 1, k = 10; i >= 0 && k > 0; --i, --k) {
pq.offer(userTweet.get(i));
}
}
}
List<Integer> res = new ArrayList<>();
while (!pq.isEmpty() && res.size() < 10) {
res.add(pq.poll());
}
return res;
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
public void follow(int followerId, int followeeId) {
userFollowing.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
public void unfollow(int followerId, int followeeId) {
userFollowing.computeIfAbsent(followerId, k -> new HashSet<>()).remove(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);
*/
// Accepted solution for LeetCode #355: Design Twitter
type Tweet struct {
count int
tweetId int
followeeId int
index int
}
type TweetHeap []*Tweet
func (h TweetHeap) Len() int { return len(h) }
func (h TweetHeap) Less(i, j int) bool { return h[i].count < h[j].count }
func (h TweetHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *TweetHeap) Push(x interface{}) {*h = append(*h, x.(*Tweet))}
func (h *TweetHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
type Twitter struct {
count int
tweetMap map[int][]*Tweet
followMap map[int]map[int]bool
}
func Constructor() Twitter {
return Twitter{tweetMap: make(map[int][]*Tweet), followMap: make(map[int]map[int]bool)}
}
func (this *Twitter) PostTweet(userId int, tweetId int) {
if _, ok := this.tweetMap[userId]; !ok {
this.tweetMap[userId] = make([]*Tweet, 0)
}
this.tweetMap[userId] = append(this.tweetMap[userId], &Tweet{count: this.count, tweetId: tweetId})
this.count -= 1
}
func (this *Twitter) GetNewsFeed(userId int) []int {
res := make([]int, 0)
minHeap := TweetHeap{}
if _, ok := this.followMap[userId]; !ok {
this.followMap[userId] = make(map[int]bool)
}
this.followMap[userId][userId] = true;
for followeeId, _ := range this.followMap[userId] {
if _, ok := this.tweetMap[followeeId]; ok {
index := len(this.tweetMap[followeeId]) - 1
tweet := this.tweetMap[followeeId][index]
heap.Push(&minHeap, &Tweet{
count: tweet.count,
tweetId: tweet.tweetId,
followeeId: followeeId,
index: index - 1})
}
}
for len(minHeap) > 0 && len(res) < 10 {
tweet := heap.Pop(&minHeap).(*Tweet)
res = append(res, tweet.tweetId)
if tweet.index >= 0 {
nextTweet := this.tweetMap[tweet.followeeId][tweet.index]
heap.Push(&minHeap, &Tweet{count: nextTweet.count,
tweetId: nextTweet.tweetId,
followeeId: tweet.followeeId,
index: tweet.index - 1})
}
}
return res
}
func (this *Twitter) Follow(followerId int, followeeId int) {
if _, ok := this.followMap[followerId]; !ok {
this.followMap[followerId] = make(map[int]bool)
}
this.followMap[followerId][followeeId] = true
}
func (this *Twitter) Unfollow(followerId int, followeeId int) {
if _, ok := this.followMap[followerId]; ok {
delete(this.followMap[followerId], followeeId)
}
}
# Accepted solution for LeetCode #355: Design Twitter
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.user_tweets = defaultdict(list)
self.user_following = defaultdict(set)
self.tweets = defaultdict()
self.time = 0
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
self.time += 1
self.user_tweets[userId].append(tweetId)
self.tweets[tweetId] = self.time
def getNewsFeed(self, userId: int) -> List[int]:
"""
Retrieve 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 herself. Tweets must be ordered from most recent to least recent.
"""
following = self.user_following[userId]
users = set(following)
users.add(userId)
tweets = [self.user_tweets[u][::-1][:10] for u in users]
tweets = sum(tweets, [])
return nlargest(10, tweets, key=lambda tweet: self.tweets[tweet])
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
self.user_following[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
following = self.user_following[followerId]
if followeeId in following:
following.remove(followeeId)
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)
// Accepted solution for LeetCode #355: Design Twitter
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
type Tweet = (Reverse<usize>, i32);
#[derive(Default)]
struct Twitter {
time: usize,
users: HashMap<i32, HashSet<i32>>,
tweets: HashMap<i32, Vec<Tweet>>,
limit: usize,
}
impl Twitter {
fn new() -> Self {
let time = 0;
let users = HashMap::new();
let tweets = HashMap::new();
let limit = 10;
Twitter {
time,
users,
tweets,
limit,
}
}
fn post_tweet(&mut self, user_id: i32, tweet_id: i32) {
self.time += 1;
let tweet: Tweet = (Reverse(self.time), tweet_id);
self.tweets.entry(user_id).or_default().push(tweet);
}
fn get_news_feed(&mut self, user_id: i32) -> Vec<i32> {
let mut pq: BinaryHeap<Tweet> = BinaryHeap::with_capacity(self.limit + 1);
let mut res: Vec<i32> = vec![];
let followers = self.users.entry(user_id).or_default();
followers.insert(user_id);
for &user in followers.iter() {
let tweets = self.tweets.entry(user).or_default();
for tweet in tweets {
pq.push(*tweet);
if pq.len() > self.limit {
pq.pop();
}
}
}
while !pq.is_empty() {
let earliest = pq.pop().unwrap();
res.push(earliest.1);
}
res.reverse();
res
}
fn follow(&mut self, follower_id: i32, followee_id: i32) {
self.users
.entry(follower_id)
.or_default()
.insert(followee_id);
}
fn unfollow(&mut self, follower_id: i32, followee_id: i32) {
self.users
.entry(follower_id)
.or_default()
.remove(&followee_id);
}
}
#[test]
fn test() {
let mut twitter = Twitter::new();
twitter.post_tweet(1, 5);
assert_eq!(twitter.get_news_feed(1), vec![5]);
twitter.follow(1, 2);
twitter.post_tweet(2, 6);
assert_eq!(twitter.get_news_feed(1), vec![6, 5]);
twitter.unfollow(1, 2);
assert_eq!(twitter.get_news_feed(1), vec![5]);
}
// Accepted solution for LeetCode #355: Design Twitter
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #355: Design Twitter
// class Twitter {
// private Map<Integer, List<Integer>> userTweets;
// private Map<Integer, Set<Integer>> userFollowing;
// private Map<Integer, Integer> tweets;
// private int time;
//
// /** Initialize your data structure here. */
// public Twitter() {
// userTweets = new HashMap<>();
// userFollowing = new HashMap<>();
// tweets = new HashMap<>();
// time = 0;
// }
//
// /** Compose a new tweet. */
// public void postTweet(int userId, int tweetId) {
// userTweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(tweetId);
// tweets.put(tweetId, ++time);
// }
//
// /**
// * Retrieve 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 herself. Tweets must be ordered
// * from most recent to least recent.
// */
// public List<Integer> getNewsFeed(int userId) {
// Set<Integer> following = userFollowing.getOrDefault(userId, new HashSet<>());
// Set<Integer> users = new HashSet<>(following);
// users.add(userId);
// PriorityQueue<Integer> pq
// = new PriorityQueue<>(10, (a, b) -> (tweets.get(b) - tweets.get(a)));
// for (Integer u : users) {
// List<Integer> userTweet = userTweets.get(u);
// if (userTweet != null && !userTweet.isEmpty()) {
// for (int i = userTweet.size() - 1, k = 10; i >= 0 && k > 0; --i, --k) {
// pq.offer(userTweet.get(i));
// }
// }
// }
// List<Integer> res = new ArrayList<>();
// while (!pq.isEmpty() && res.size() < 10) {
// res.add(pq.poll());
// }
// return res;
// }
//
// /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
// public void follow(int followerId, int followeeId) {
// userFollowing.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
// }
//
// /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
// public void unfollow(int followerId, int followeeId) {
// userFollowing.computeIfAbsent(followerId, k -> new HashSet<>()).remove(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);
// */
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.