const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

Design Twitter LeetCode 355 Guide

LeetCode 355 asks you to build a mini social network from scratch — combining hash maps for follow/unfollow, linked lists for tweets, and a max-heap to merge K sorted feeds into a single timeline.

9 min read|

Design Twitter combines OOP, hash maps, and heap merge

LeetCode 355 — the mini system design that bridges algorithms and real interviews

Design Twitter Bridges Algorithms and System Design

Design Twitter (#355) is the LeetCode problem that bridges algorithms and system design — it literally asks you to build a mini social network. Unlike most LeetCode problems that test a single technique, this one requires you to combine multiple data structures and think about how they interact. It is one of the few medium-difficulty problems that genuinely prepares you for system design interviews.

The problem asks you to implement four methods: postTweet, getNewsFeed, follow, and unfollow. On the surface these sound simple, but the news feed method hides a classic algorithmic challenge — merging K sorted lists. If you have solved Merge K Sorted Lists (#23), you already know the core technique. The design twitter leetcode problem wraps that technique inside an object-oriented shell.

This walkthrough covers the data structure choices, the heap-based feed merge, and the edge cases that trip up most candidates. By the end, you will have a clean implementation and a mental model that transfers directly to real system design rounds.

What makes this problem special is that every component has a real-world analog. The followee set maps to a social graph. The tweet list maps to a user timeline. The heap merge maps to the algorithmic core of a real news feed service. Understanding how these pieces fit together gives you a framework for approaching any design problem that combines data modeling with algorithmic efficiency.

Understanding the Design Twitter Problem

LeetCode 355 gives you a Twitter class with four operations. postTweet(userId, tweetId) creates a new tweet. getNewsFeed(userId) returns the 10 most recent tweet IDs from the user and the people they follow. follow(followerId, followeeId) adds a follow relationship. unfollow(followerId, followeeId) removes a follow relationship.

The key constraint is that getNewsFeed must return tweets sorted by recency, and it must consider tweets from all followed users plus the user themselves. This is not a simple lookup — it requires merging multiple sorted streams into one. The leetcode 355 solution hinges on how efficiently you can perform this merge.

Think of each user as having their own timeline — a list of tweets sorted by timestamp. When someone requests their news feed, you need to merge all the timelines of people they follow (including their own) and extract the top 10. This is exactly the Merge K Sorted Lists problem wearing a different outfit.

One detail that candidates often overlook: the problem says "most recent" but does not specify how recency is determined. In your implementation, you need a global ordering mechanism — a monotonically increasing timestamp or counter. Without this, you cannot compare tweets from different users. This is a small design decision that has big implications for correctness.

ℹ️

Real-World Relevance

Design Twitter (#355) literally appears in Twitter/X interviews — it is the LeetCode problem that most directly maps to a real system design question.

Data Structure Design for Twitter

The design twitter OOP solution relies on three core data structures. First, a HashMap from userId to a Set of followee IDs — this gives O(1) follow and unfollow. Second, a HashMap from userId to a list of tweets, where each tweet stores the tweetId and a global timestamp. Third, a global timestamp counter that increments with every new tweet to establish ordering.

The follow/unfollow system is straightforward. When user A follows user B, you add B to A's followee set. When user A unfollows user B, you remove B from the set. The set prevents duplicates and makes both operations constant time. One important detail: a user should always see their own tweets, so you can either auto-add each user to their own followee set or handle that explicitly in getNewsFeed.

For tweets, each user maintains an ordered list where the most recent tweet is at the head. Because we attach a global timestamp to every tweet, we can compare tweets from different users. This ordering is what makes the merge step possible — each user's tweet list is already sorted by time, giving us K sorted lists to merge.

  • followMap: HashMap<userId, Set<followeeId>> — O(1) follow/unfollow
  • tweetMap: HashMap<userId, List<(timestamp, tweetId)>> — ordered by recency
  • Global timestamp counter — increments on every postTweet call
  • Each user's tweet list is pre-sorted, enabling efficient merge

The News Feed: Merge K Sorted Lists

The getNewsFeed method is where the real algorithmic work happens. You need to merge the tweet lists of all followed users (plus the user themselves) and return the 10 most recent tweets. This is a classic merge K sorted feeds problem, and the optimal approach uses a max-heap (priority queue).

Here is how it works. For each followee (including self), take the most recent tweet and push it onto a max-heap keyed by timestamp. Then pop the max element — that is the most recent tweet overall. After popping, push the next tweet from the same user's list onto the heap. Repeat until you have 10 tweets or the heap is empty.

This approach runs in O(K log K) for K followees when fetching 10 tweets, because each heap operation is O(log K) and you perform at most 10 iterations (plus K initial insertions). Compare this to the naive approach of collecting all tweets into one list and sorting — that would be O(N log N) where N is the total number of tweets across all followees. The heap approach is dramatically faster for users who follow many active accounts.

If you have solved Merge K Sorted Lists (#23) on LeetCode, this is the exact same pattern. The only difference is that instead of merging linked lists, you are merging arrays of tweets. The data structure changes, but the algorithm is identical — initialize the heap with the head of each list, pop the max, advance the pointer, and push the next element.

A common follow-up question in interviews is: what if we need more than 10 tweets? The heap approach scales gracefully — just increase the pop count. What if we need real-time updates? That moves into push-based fan-out territory, which is the system design version of this problem. The LeetCode version uses pull-based merging, but understanding both models shows depth in your design thinking.

💡

Merge K Insight

The news feed is just Merge K Sorted Lists — each followed user's tweet list is sorted by timestamp. Use a max-heap to extract the 10 most recent across all lists.

Implementation Walkthrough

Let us walk through each method in the design twitter explained approach. The constructor initializes the two hash maps and sets the timestamp counter to zero. No pre-allocation is needed because users are created lazily when they first interact with the system.

For postTweet, you store a tuple of (timestamp, tweetId) at the front of the user's tweet list and increment the global counter. For follow, you add the followeeId to the follower's set — making sure not to add yourself (or handling self-follow in getNewsFeed). For unfollow, you remove the followeeId from the set, with a guard to avoid errors when the relationship does not exist.

For getNewsFeed, you gather all followee IDs (including self), seed the max-heap with the most recent tweet from each, and then pop up to 10 times. Each pop gives you the next most recent tweet, and you push the following tweet from that same user to keep the merge going. The result is a list of up to 10 tweetIds in reverse chronological order.

  1. 1Initialize: followMap = {}, tweetMap = {}, timestamp = 0
  2. 2postTweet(userId, tweetId): prepend (timestamp++, tweetId) to tweetMap[userId]
  3. 3follow(followerId, followeeId): add followeeId to followMap[followerId]
  4. 4unfollow(followerId, followeeId): remove followeeId from followMap[followerId] if present
  5. 5getNewsFeed(userId): collect followees + self, seed heap with each user's latest tweet, pop 10 times

Edge Cases and Gotchas

The follow unfollow system has several edge cases that interviewers love to probe. First, a user unfollowing someone they never followed should be a no-op — do not throw an error. Second, a user calling getNewsFeed before posting or following anyone should return an empty list. Third, the same user calling follow on the same person multiple times should not create duplicates, which is why a Set is the right choice.

Another subtle case is the interaction between posting and following. If user A follows user B after B has already posted tweets, A's news feed should still include B's past tweets. This works naturally with our design because getNewsFeed reads the full tweet list at query time rather than maintaining a pre-built timeline.

Time and space complexity for the full solution: postTweet is O(1), follow is O(1), unfollow is O(1), and getNewsFeed is O(K log K) where K is the number of followees. Space is O(U + T) where U is total users and T is total tweets. This matches what interviewers expect for an optimal leetcode 355 solution.

Performance-wise, the getNewsFeed operation dominates the cost profile. If a user follows thousands of accounts, the initial heap seeding takes O(K) time where K is the followee count. In practice, capping the number of followees or using a fan-out-on-write approach addresses this — but for the LeetCode problem, the pull-based merge is the expected solution and performs well within the given constraints.

  • Unfollow a non-followed user: no-op, no error
  • getNewsFeed with no tweets or follows: return empty list
  • Duplicate follow calls: Set handles idempotency automatically
  • Following after someone already posted: feed includes past tweets
  • User with zero followees: feed still shows their own tweets
⚠️

Common Bug

Users should see their OWN tweets in the feed — don't forget to include self in the followee set. A common bug is only merging tweets from people you follow, excluding your own.

What Design Twitter Teaches You

Design Twitter is one of the best problems on LeetCode for building design intuition. It forces you to think about data modeling (how to represent users, tweets, and relationships), algorithm selection (why a heap beats a sort for the feed), and API design (clean method signatures with predictable behavior). These are exactly the skills that system design interviews evaluate.

The connection to Merge K Sorted Lists (#23) is worth highlighting. Once you recognize that getNewsFeed is a K-way merge, the entire problem simplifies. This is the pattern recognition skill that separates candidates who grind blindly from those who solve problems efficiently. If you can spot the merge-K pattern inside a design wrapper, you are thinking at the right level.

If you are preparing for interviews at companies that build social features — Twitter/X, Meta, LinkedIn, TikTok — this problem is essential practice. It shows up in both coding rounds and system design rounds, just at different levels of abstraction. Drill the implementation with YeetCode flashcards so the data structure choices become automatic, and you can spend your interview time on communication instead of fumbling with hash map initialization.

Beyond the specific techniques, Design Twitter teaches you how to decompose a product requirement into data structures and algorithms. The requirement "show me my feed" becomes "merge K sorted lists with a heap." The requirement "follow a user" becomes "add to a hash set." This translation skill — from product language to engineering primitives — is what separates strong candidates from those who can only solve problems when they are handed a clean algorithmic statement.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now