15% off all plans & roadmaps Use code

See plans

Design Twitter

Updated

TL;DR: Build a Twitter class with post, follow, unfollow and a news feed of the 10 newest tweets. Keep each user's tweets in posting order and merge the followed users' lists with a max-heap. A feed then never touches more than about 10 tweets plus one head per source.

Problem

Implement a Twitter class that stores tweets and follow relationships. The constructor takes no arguments and starts an empty service. Every tweetId is unique, and tweets are ordered by when their postTweet calls happen: a later call means a more recent tweet.

  • postTweet(userId, tweetId) records a tweet by userId. It returns nothing.
  • follow(followerId, followeeId) makes followerId follow followeeId. It returns nothing.
  • unfollow(followerId, followeeId) removes that relationship if it exists. It returns nothing.
  • getNewsFeed(userId) returns up to the 10 most recent tweet IDs posted by userId or by any user userId currently follows, newest first. If there are no eligible tweets, return an empty list. This call does not change any stored state.

Example 1

Input: ["Twitter", "postTweet", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[],[7,501],[7,502],[7],[7,12],[12,880],[7],[7,12],[7]]
Output: [null,null,null,[502,501],null,null,[880,502,501],null,[502,501]]
Explanation: User 7 first sees their own two tweets. After following user 12, user 7 also sees tweet 880. Unfollowing user 12 removes it again.

Example 2

Input: ["Twitter", "follow", "postTweet", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed", "unfollow", "getNewsFeed"]
[[],[4,9],[9,31],[4,44],[4],[4,9],[4],[4,9],[22]]
Output: [null,null,null,null,[44,31],null,[44],null,[]]
Explanation: A follow created before either tweet is posted still lets user 4 see user 9's tweet. The second unfollow does nothing, and user 22 has no eligible tweets.

Example 3

Input: ["Twitter", "postTweet", "follow", "postTweet", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[],[15,700],[3,15],[3,701],[3,15],[15,702],[3],[3,15],[3]]
Output: [null,null,null,null,null,null,[702,701,700],null,[701]]
Explanation: User 3 follows user 15, and the repeated follow changes nothing. The first feed lists the three tweets in reverse posting order. After the unfollow, only user 3's own tweet remains.

Constraints

  • The first operation is Twitter, and its argument list is empty.
  • 1 <= operations.length <= 10^5.
  • Every later operation is postTweet, getNewsFeed, follow, or unfollow.
  • userId, followerId, and followeeId are integers.
  • tweetId is an integer, and every tweetId is unique across all postTweet calls.
  • followerId != followeeId for every follow and unfollow call.
  • unfollow may name a relationship that does not exist. Such a call is valid and has no effect.

Constraints that matter

  • Up to 10^5 operations means a feed call cannot afford to sort every eligible tweet each time. A user who follows many busy accounts would make that cost grow with the whole history.
  • The feed holds at most 10 tweets, so work should depend on 10 and on the number of sources, not on the total number of tweets stored.
  • Every tweetId is unique, and posting order defines recency. A global counter gives each tweet a strict timestamp, so ties never happen.
  • unfollow may target a relationship that does not exist, and follow may repeat. Store followees in a set so both calls are safe and idempotent.
  • followerId != followeeId, so a user is never in their own follow set. You still add the user as a source yourself in every feed call.

View on LeetCode

Hints

Hint 1

The feed is a merge.

Hint 2

Store each user's tweets as (timestamp, tweetId) pairs in a per-user list, and each user's followees in a set.

Solution

Intuition

The feed is a merge. Each eligible user owns a list of tweets already sorted by time, because you append in posting order. You want the 10 newest across several sorted lists. That is the k-way merge pattern.

Picture a stack of sorted mail trays, one per followed account, each with the newest letter on top. You keep a small tray of the current top letters, always pull out the newest one, and slide the next older letter from that same account's pile into the tray. The heap is the tray of tops, and the per-user lists are the piles.

The output is tiny and fixed. Only 10 tweets are ever returned, yet the history can be huge. Any solution that touches every eligible tweet pays for work the answer never uses. The signal for a heap is several sorted sources where you need only the first few merged items.

A max-heap works because the newest unseen tweet overall is always the newest unseen tweet of some single user. So the heap needs only one entry per source: that user's newest tweet not yet taken. When you pop an entry, the only new candidate is the next older tweet from the same user. You push it and continue.

That gives a feed cost of about F log F for F sources, with at most 10 pops. Posting and following stay O(1), since they only append to a list or edit a set.

Watch the pattern animation

Worked example

Input: operations = ["Twitter", "follow", "postTweet", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed", "unfollow", "getNewsFeed"]
arguments = [[], [4, 9], [9, 31], [4, 44], [4], [4, 9], [4], [4, 9], [22]]
Output: [null,null,null,null,[44,31],null,[44],null,[]]
Explanation: User 4 follows user 9 before any tweet exists. User 9 posts 31 and user 4 posts 44, so user 4's feed is [44, 31]. After unfollowing user 9 only 44 remains. The second unfollow changes nothing, and user 22 has posted nothing and follows nobody, so that feed is empty.

Approach 1: Brute force: collect and sort

Store each user's tweets as (timestamp, tweetId) pairs in a per-user list, and each user's followees in a set. For a feed, gather every tweet from the user and all followees into one list, sort it by timestamp descending, and cut it to 10.

This is correct because the sorted list is exactly the eligible history in recency order. It does far more work than the answer needs.

Steps

  1. Keep a global counter time that increases by 1 on every postTweet.
  2. On postTweet, append (time, tweetId) to the author's list.
  3. On follow, add the followee to the follower's set. On unfollow, discard it if present.
  4. On getNewsFeed, build the source set: the user plus the followees.
  5. Append every tweet of every source to one list.
  6. Sort that list by timestamp, newest first.
  7. Return the tweet IDs of the first 10 entries.

Dry run

Run the example. follow(4, 9) stores following[4] = {9}. postTweet(9, 31) stores (1, 31) for user 9. postTweet(4, 44) stores (2, 44) for user 4.

First getNewsFeed(4): sources are {4, 9}. The collected list is [(2, 44), (1, 31)] in some order. Sorted descending it is [(2, 44), (1, 31)], so the result is [44, 31].

unfollow(4, 9) empties the set. The next getNewsFeed(4) collects only user 4's list [(2, 44)] and returns [44]. The second unfollow finds nothing to remove. getNewsFeed(22) has source set {22} with no tweets, so it returns [].

Complexity

TimeO(T log T) per getNewsFeed, O(1) for the other calls
SpaceO(T) for the feed call, plus O(total tweets + follows) stored

Let T be the total number of tweets by the user and everyone the user follows. Collecting them touches each tweet once, which is O(T), and sorting costs O(T log T). Posting and following only append to a list or edit a set, so they are O(1). The temporary list holds all T tweets, so a feed call needs O(T) extra space.

PythonTested in our runner

from typing import List, Optional

class Twitter:
    def __init__(self):
        self.time = 0
        self.tweets = {}      # userId -> list of (time, tweetId)
        self.following = {}   # userId -> set of followeeIds

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.time += 1
        self.tweets.setdefault(userId, []).append((self.time, tweetId))

    def getNewsFeed(self, userId: int) -> List[int]:
        sources = set(self.following.get(userId, set()))
        sources.add(userId)
        collected = []
        for u in sources:
            collected.extend(self.tweets.get(u, []))
        collected.sort(reverse=True)  # newest timestamp first
        return [tweetId for _, tweetId in collected[:10]]

    def follow(self, followerId: int, followeeId: int) -> None:
        self.following.setdefault(followerId, set()).add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.following.get(followerId, set()).discard(followeeId)

Approach 2: Scan the global log backwards

What's slow: the brute force sorts every eligible tweet, even though you keep only 10. The sort is wasted, because tweets are already in posting order.

The insight that fixes it: keep one global log of (author, tweetId) in posting order. Walk it from the newest entry backwards, keep entries whose author is the user or a followee, and stop at 10. No sorting and no timestamps are needed, since position in the log is the time.

Steps

  1. Keep one list log of (author, tweetId), appended on every postTweet.
  2. Keep a set of followees per user, edited by follow and unfollow.
  3. On getNewsFeed, start an empty result and an index at the last log entry.
  4. Move the index backwards one entry at a time.
  5. If the entry's author is the user or is in the follow set, add its tweet ID to the result.
  6. Stop when the result has 10 tweets or the index passes the start of the log.
  7. Return the result.

Dry run

On the example, the log after both posts is [(9, 31), (4, 44)]. following[4] is {9} for the first feed.

getNewsFeed(4) starts at the last entry (4, 44). Author 4 is the user, so the result becomes [44]. The next entry is (9, 31). Author 9 is followed, so the result becomes [44, 31]. The log is exhausted and the answer is [44, 31].

After unfollow(4, 9) the follow set is empty. The scan takes (4, 44), then skips (9, 31) because 9 is not followed. The result is [44].

For user 22 both entries are skipped and the result is [].

Complexity

TimeO(N) per getNewsFeed in the worst case, O(1) for the other calls
SpaceO(1) extra per feed call, plus O(N + follows) stored

Let N be the total number of tweets ever posted. A feed call visits each log entry at most once and does an O(1) set lookup per entry, so it is O(N) in the worst case. That worst case happens when the user has fewer than 10 eligible tweets and the scan reaches the start of the log.

Posting appends one entry and follow edits one set, so both are O(1). The result holds at most 10 IDs, so extra space per call is constant.

PythonTested in our runner

from typing import List, Optional

class Twitter:
    def __init__(self):
        self.log = []         # (author, tweetId) in posting order
        self.following = {}   # userId -> set of followeeIds

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.log.append((userId, tweetId))

    def getNewsFeed(self, userId: int) -> List[int]:
        followed = self.following.get(userId, set())
        feed = []
        for i in range(len(self.log) - 1, -1, -1):
            author, tweetId = self.log[i]
            if author == userId or author in followed:
                feed.append(tweetId)
                if len(feed) == 10:
                    break
        return feed

    def follow(self, followerId: int, followeeId: int) -> None:
        self.following.setdefault(followerId, set()).add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.following.get(followerId, set()).discard(followeeId)
K-way Merge pattern infographic for Design Twitter

Solution pattern

K-way Merge

Part of Heap (Priority Queue) Patterns

Approach 3: Per-user lists with a max-heap mergeOptimalK-way Merge

What's slow: the backward scan still reads every tweet by strangers. If the user follows two quiet accounts in a service with 100,000 tweets from others, the scan crosses the whole log to find a handful of results.

The insight that fixes it: give each user their own list, sorted by time because you append. A feed is then a merge of F sorted lists, and you need only the first 10 merged items.

Put the newest tweet of each source in a max-heap keyed by timestamp. Pop the top, record it, and push the next older tweet of that same source. Tweets by unrelated users are never read.

Why it is correct. The heap always holds the newest not-yet-taken tweet from each source, so the global newest remaining tweet must be one of those tops. Popping it and pushing that source's next older tweet keeps this invariant. Since each source list is already in time order, no older tweet can jump ahead of a newer one from another source.

Steps

  1. Keep a global counter time. On postTweet, append (time, tweetId) to the author's list.
  2. Keep a set of followees per user for follow and unfollow.
  3. On getNewsFeed, build the source set: the user plus the followees.
  4. For each source with tweets, push its last tweet into the heap as (time, tweetId, source, index).
  5. While the heap is not empty and the feed has fewer than 10 IDs, pop the entry with the largest time.
  6. Append its tweet ID to the feed.
  7. If its index is above 0, push the same source's tweet at index - 1.
  8. Return the feed.

Dry run

On the example, user 9 holds [(1, 31)] and user 4 holds [(2, 44)]. The first getNewsFeed(4) has sources {4, 9}. The heap starts as [(2, 44, user 4, idx 0), (1, 31, user 9, idx 0)].

Pop (2, 44): feed [44], and index 0 means nothing to push. Pop (1, 31): feed [44, 31]. The heap is empty, so the result is [44, 31].

After unfollow(4, 9), sources are {4}, the heap holds only (2, 44), and the result is [44]. For user 22 no source has tweets, the heap starts empty, and the result is []. The full step table is below.

StepCallSourcesHeap after step (time, id)Feed
1follow(4, 9)
2postTweet(9, 31)user 9 list: [(1,31)]
3postTweet(4, 44)user 4 list: [(2,44)]
4agetNewsFeed(4): seed{4, 9}[(2,44), (1,31)][]
4bpop (2,44){4, 9}[(1,31)][44]
4cpop (1,31){4, 9}[][44, 31]
5unfollow(4, 9)
6agetNewsFeed(4): seed{4}[(2,44)][]
6bpop (2,44){4}[][44]
7unfollow(4, 9)no-op
8getNewsFeed(22): seed{22}[][]

Complexity

TimeO(F log F) per getNewsFeed, O(1) for the other calls
SpaceO(F) extra per feed call, plus O(total tweets + follows) stored

Let F be the number of sources: the user plus the followees. Seeding pushes at most F entries, which costs O(F log F) with individual pushes and O(F) with heapify.

The loop pops at most 10 times and pushes at most once per pop. That adds at most 20 heap operations of O(log F) each, which is O(log F). The heap never holds more than F entries, because each pop is replaced by at most one push from the same source.

Posting appends to one list and following edits one set, so both are O(1).

PythonTested in our runner

import heapq
from typing import List, Optional

class Twitter:
    def __init__(self):
        self.time = 0
        self.tweets = {}      # userId -> list of (time, tweetId), oldest first
        self.following = {}   # userId -> set of followeeIds

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.time += 1
        self.tweets.setdefault(userId, []).append((self.time, tweetId))

    def getNewsFeed(self, userId: int) -> List[int]:
        sources = set(self.following.get(userId, set()))
        sources.add(userId)
        heap = []
        for u in sources:
            lst = self.tweets.get(u)
            if lst:
                i = len(lst) - 1
                # negate time so Python's min-heap acts as a max-heap
                heap.append((-lst[i][0], lst[i][1], u, i))
        heapq.heapify(heap)
        feed = []
        while heap and len(feed) < 10:
            _, tweetId, u, i = heapq.heappop(heap)
            feed.append(tweetId)
            if i > 0:
                t = self.tweets[u][i - 1]
                heapq.heappush(heap, (-t[0], t[1], u, i - 1))
        return feed

    def follow(self, followerId: int, followeeId: int) -> None:
        self.following.setdefault(followerId, set()).add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.following.get(followerId, set()).discard(followeeId)

Common mistakes

  • Forgetting to add the user to their own sources in getNewsFeed. A user with no followees would get an empty feed. Build the source set as the followees plus userId.
  • Using following[userId].remove(followeeId) without a guard. It raises an error in Python when the key or the element is missing, and unfollow is allowed to name a missing relationship. Use discard on a defaulted set, or check for null first.
  • Using the tweet ID as the ordering key instead of a timestamp. Tweet IDs are unique but not increasing, so the feed would come out in the wrong order. Keep a global counter that increments on every postTweet.
  • Pushing every tweet of every source into the heap at the start. That sorts the whole history and removes the benefit of the merge. Push only the last tweet of each source, then push the next older one after each pop.
  • Forgetting to push the replacement after a pop (if i > 0 branch missing). A user with three tweets would contribute only one to the feed. After each pop, push tweets[source][index - 1] when the index is above 0.
  • In Python, pushing (time, ...) into heapq without negating the time. heapq is a min-heap, so you would return the oldest tweets first. Push -time, or negate the comparison in a language that takes a comparator.
  • Storing the feed state inside the object, for example by deleting popped tweets from the user's list. getNewsFeed must not change state, so a second call would then return fewer tweets. Track a read position in the heap entry only.

Edge cases

  • A user who never posted and follows nobody: getNewsFeed returns an empty list.
  • unfollow on a relationship that never existed, or called twice: no effect and no error.
  • A repeated follow: the set already holds the followee, so the relationship is unchanged and tweets are not duplicated in the feed.
  • Following a user before they post: later tweets by that user must appear in the follower's feed.
  • More than 10 eligible tweets: only the 10 newest appear, newest first.
  • A user follows someone, then unfollows them: that user's older tweets disappear from the feed, but the user's own tweets stay.

Follow-ups interviewers ask

How would you make getNewsFeed cheaper when a user follows many accounts?
The heap already limits work to F log F, where F is the number of followees. To do better, cache each user's recent 10 tweets and fan out on write: when a user posts, push the tweet into each follower's precomputed feed. Reads become O(10), and writes cost the number of followers. The trade-off is heavy writes for accounts with many followers, so real systems often mix both.
Can you do getNewsFeed without a heap?
Yes. The backward scan of one global log needs no heap and no sort, and it stops after 10 matches. Its worst case is O(N) in the total tweets posted, so it is slower when the user's sources are quiet. The heap version only reads the sources' own lists, so it is better when the service has many more tweets than the user's circle.
How would you reduce memory if every user posts millions of tweets?
A feed only ever needs the newest 10 tweets of each source, because a single source cannot contribute more than 10 results. Keep only the last 10 tweets per user in the feed structure, and move older tweets to cold storage. The heap merge then touches at most 10 entries per source, and each source list is capped at a constant size.

Design Twitter FAQ

What is the time complexity of Design Twitter?

With per-user lists and a heap, postTweet, follow and unfollow are O(1). getNewsFeed is O(F log F), where F is the number of sources: the user plus the followees. The heap never holds more than F entries and the feed pops at most 10 times. Space for one feed call is O(F).

Why use a heap for Design Twitter?

The feed merges several lists that are already sorted by time, and you only need the 10 newest results. A max-heap holding one candidate per source gives the newest tweet in O(log F) and reveals the next candidate after each pop. That avoids sorting every eligible tweet. This is the k-way merge pattern.

Can Design Twitter be solved in O(1) extra space?

Not with a heap or a sort, since both need space proportional to the number of sources. The backward scan of a global log uses O(1) extra space per feed call, because it keeps only the result list of at most 10 IDs. The cost is a worst-case O(N) scan. You also still store all tweets and follows, which no solution can avoid.

How do I solve LeetCode 355 in Python?

Keep a counter, a dict from user to a list of (time, tweetId), and a dict from user to a set of followees. In getNewsFeed, push the last tweet of each source into a heapq as (-time, tweetId, user, index). Pop up to 10 times and push the previous tweet of the popped source each time. The Python code on this page does exactly that.

Why does the heap hold only one tweet per user?

A user's newest unseen tweet always beats that user's older ones. So the overall newest unseen tweet must be the newest unseen tweet of some user. After you take it, only that user's next older tweet can become the new candidate. Every other source still shows the same candidate as before.

Does the order of follow and postTweet matter for the feed?

No. The feed is computed from the current follow set and the stored tweets at call time. Following a user before or after they post gives the same feed, and unfollowing hides their tweets immediately. Only the relative order of the posts themselves defines recency.

Asked at

See which companies ask this — Pro

Practise it