Problem 355

Abstract / Summary

Design a social media system that lets users post tweets and follow others to see their updates in the order they are posted.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0355.py

class Twitter:

    def __init__(self):
        self.tweets = {}
        self.feed   = defaultdict(list)
        self.a2b    = defaultdict(set)

    def postTweet(self, userId: int, tweetId: int) -> None:
        seq = len(self.tweets)
        self.tweets[seq] = tweetId
        self.feed[userId].append(seq)

    def getNewsFeed(self, userId: int) -> List[int]:
        seqs = self.feed[userId].copy()
        for i in self.a2b[userId]:
            seqs += self.feed[i]

        result = []
        for s in sorted(seqs, reverse = True):
            result.append(self.tweets[s])
            if len(result) == 10:
                break

        return result

    def follow(self, followerId: int, followeeId: int) -> None:
        if followerId != followeeId:
            self.a2b[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.a2b[followerId].discard(followeeId)
31 lines | 958 bytes | submitted September 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (700k+ submissions).

Typical patterns to solve this problem:
  • Design
  • Hash Table
  • Heap (Priority Queue)
  • Linked List
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Twitter class implements a minimal in-memory model of a micro-blogging service. It supports posting tweets, retrieving a personalized news feed, and managing follow relationships between users. All state is kept in Python dictionaries and defaultdict containers, enabling constant-time updates for most operations. The design emphasizes simplicity while still delivering the essential behavior expected from a social feed.

Core Data Structures

The constructor creates three primary containers:

self.tweets = {}
self.feed   = defaultdict(list)
self.a2b    = defaultdict(set)

self.tweets maps a monotonically increasing sequence number to the actual tweet identifier, preserving insertion order. self.feed stores, for each user, a list of sequence numbers representing that user’s own tweets. self.a2b records follow relationships as a set of followees for each follower, allowing O(1) membership checks and duplicate-free storage.

Posting a Tweet

When a user posts a tweet, the method computes a sequence number based on the current size of self.tweets. This sequence number serves as a global timestamp, guaranteeing that newer tweets have larger keys.

seq = len(self.tweets)
self.tweets[seq] = tweetId
self.feed[userId].append(seq)

The tweet identifier is stored under the new sequence key, and the sequence is appended to the author’s personal feed list. Because the sequence is derived from the dictionary length, it automatically increments with each call, ensuring a total ordering without requiring an external clock.

Retrieving the News Feed

The getNewsFeed method assembles a list of up to ten recent tweet identifiers visible to a given user. It begins by copying the user’s own sequence list, then iterates over each followee to concatenate their sequences.

seqs = self.feed[userId].copy()
for i in self.a2b[userId]:
    seqs += self.feed[i]

The combined list is sorted in descending order of sequence numbers, which corresponds to reverse chronological order. The method then walks the sorted list, translating each sequence back to its tweet identifier via self.tweets. It stops once ten identifiers have been collected.

result = []
for s in sorted(seqs, reverse = True):
    result.append(self.tweets[s])
    if len(result) == 10:
        break
return result

By limiting the output to ten items, the method avoids unnecessary processing of older tweets, even when a user follows many active accounts.

Following a User

The follow method adds a followee to the follower’s set, provided the two identifiers differ. The set structure automatically prevents duplicate entries.

if followerId != followeeId:
    self.a2b[followerId].add(followeeId)

The guard against self-following eliminates a potential source of redundant data and ensures that a user’s own tweets are not double-counted when constructing the feed.

Unfollowing a User

Unfollowing removes a followee from the follower’s set using discard, which silently does nothing if the relationship does not exist.

self.a2b[followerId].discard(followeeId)

This choice of method avoids raising an exception for non-existent relationships, simplifying client code that may issue redundant unfollow requests.

Edge Cases Handled

The implementation gracefully handles several boundary conditions:

  • When a user has never posted a tweet, self.feed[userId] yields an empty list, and the news feed returns an empty result without error.
  • If a user follows no one, the loop over self.a2b[userId] iterates over an empty set, leaving only the user’s own tweets in consideration.
  • Attempting to follow oneself is ignored, preventing self-references that could otherwise inflate the feed.
  • Unfollowing a non-existent relationship does not raise an exception because discard safely ignores missing elements.
  • The getNewsFeed method caps the output at ten items, so even if a user follows many active accounts, the method never attempts to process more than necessary for the final result.

Performance Optimizations

The code leverages several implicit optimizations:

  • Using a global sequence number as a surrogate timestamp eliminates the need for real-time clocks and enables fast integer comparisons during sorting.
  • Storing followees in a set provides O(1) addition, removal, and membership checks, which is crucial when users frequently modify their follow lists.
  • The per-user feed list stores only sequence numbers, keeping the memory footprint small compared to storing full tweet objects.
  • Copying the user’s own feed list before concatenation ensures that the original list remains unchanged, allowing safe reuse across multiple feed requests.
  • Sorting is performed on a flat list of sequence numbers rather than on tweet objects, reducing the amount of data moved during the sort operation.
  • The early break after collecting ten tweets prevents unnecessary iteration over the remainder of the sorted list, saving CPU cycles when the combined sequence list is large.
written by openai gpt

ELI5 - Simplified Explanation

Imagine a magical toy box that helps people share their favorite drawings. At the very beginning, the box is empty and ready to store pictures.

When a person posts a drawing, it gets a special number so everyone knows exactly when it was added. That drawing is then carefully put into the person's own collection.

The news feed is like a big bulletin board where you can see all the drawings from you and your friends. To show these, the computer gathers all the drawings from the people you follow and puts them in a pile. It looks at the special numbers to sort them from newest to oldest. It picks out the ten newest drawings to show on the board so you can see what is happening right now.

Sometimes you might want to look at a new friend's drawings. You can follow them, which acts like putting a sticker by their name in a notebook. This tells the computer that you want to see their pictures on your board too. If you ever change your mind and do not want to see their pictures anymore, you just take that sticker off. The computer remembers who you are still following and only shows drawings from those people.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.58 | σ = 1.76

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 Java
fengvyi C++
JoshCrozier JS
linouk23 Python
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 Java
fengvyi C++
JoshCrozier JavaScript
linouk23 Python
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
34 links | 23 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

11 solutions   September 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality