#355

Design Twitter

Medium
Hash TableLinked ListDesignHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a combination of a hash map and a priority queue to efficiently manage tweets and retrieve the most recent ones. This reduces the time complexity significantly while maintaining clarity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a hash map to store user follow relationships.
  2. 2Step 2: Store tweets in a list with timestamps to maintain order.
  3. 3Step 3: Use a priority queue to retrieve the 10 most recent tweets efficiently.
solution.py29 lines
1from collections import defaultdict, deque
2import heapq
3
4class Twitter:
5    def __init__(self):
6        self.tweets = []
7        self.followed = defaultdict(set)
8        self.time = 0
9
10    def postTweet(self, userId, tweetId):
11        self.tweets.append((self.time, userId, tweetId))
12        self.time += 1
13
14    def getNewsFeed(self, userId):
15        feed = []
16        followed_users = self.followed[userId] | {userId}
17        for time, uid, tid in reversed(self.tweets):
18            if uid in followed_users:
19                feed.append(tid)
20                if len(feed) == 10:
21                    break
22        return feed
23
24    def follow(self, followerId, followeeId):
25        self.followed[followerId].add(followeeId)
26
27    def unfollow(self, followerId, followeeId):
28        if followerId != followeeId:
29            self.followed[followerId].discard(followeeId)

Complexity note: The time complexity is O(n) for getting the news feed since we may need to check all tweets in the worst case, but we only keep the last 10 in our feed. The space complexity is O(n) due to storing all tweets and user relationships.

  • 1Using a hash map for user relationships allows for efficient follow/unfollow operations.
  • 2Storing tweets with timestamps helps maintain the order of tweets.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.