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)
Difficulty
and has an acceptance rate of about 45% (700k+ submissions).
Typical patterns to solve this problem:
- Design
- Hash Table
- Heap (Priority Queue)
- Linked List
AI Disclaimer
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.
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
discardsafely ignores missing elements. - The
getNewsFeedmethod 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
setprovides 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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 643: Maximum Average Subarray I
- problem 1431: Kids With the Greatest Number of Candies
- problem 310: Minimum Height Trees
- problem 334: Increasing Triplet Subsequence
- problem 368: Largest Divisible Subset
- problem 382: Linked List Random Node
- problem 398: Random Pick Index
- problem 1004: Max Consecutive Ones III
- problem 1318: Minimum Flips to Make a OR b Equal to c
- problem 1679: Max Number of K-Sum Pairs
Extra
- 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