Design Twitter
Detailed guide and Python implementation for the 'Design Twitter' problem.
1. Узнать
The 'Design Twitter' problem is a key challenge in the Heap / Priority Queue section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Design Twitter.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Design Twitter carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Постановка задачи
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed.
Implement the Twitter class:
- Twitter() Initializes your twitter object.
- postTweet(userId: int, tweetId: int) Composes a new tweet with ID tweetId by the user userId.
- getNewsFeed(userId: int) -> List[int] Retrieves the 10 most recent tweet IDs in the user's news feed.
- follow(followerId: int, followeeId: int) The user with ID followerId started following the user with ID followeeId.
- unfollow(followerId: int, followeeId: int) The user with ID followerId started unfollowing the user with ID followeeId.
Input is a list of operations and arguments. Implement a function twitter(operations: list, arguments: list) -> list that returns a list of results (None for constructor/postTweet/follow/unfollow, and List[int] for getNewsFeed).
- •1 <= userId, followerId, followeeId <= 500
- •0 <= tweetId <= 10^4
- •All the tweets have unique IDs
- •At most 30000 calls will be made in total
Примеры
operations = ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"], arguments = [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
[None, None, [5], None, None, [6, 5], None, [5]]
User 1 posts tweet 5. News feed: [5]. User 1 follows 2. User 2 posts tweet 6. News feed: [6, 5]. User 1 unfollows 2. News feed: [5].
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Готовы решить?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Интервью: идеи и вариации
Разбивка анализа сложности
Почему время: Directly evaluates all possibilities.
Почему космос: Uses standard local memory.
Почему время: Optimized paths reduce total operations.
Почему космос: May trade memory for speed.
Оптимизированный код Python для решения
Оптимизированный код Python для решения
import heapq, collections
class TwitterOpt:
def __init__(self):
self.count = 0
self.tweetMap = collections.defaultdict(list)
self.followMap = collections.defaultdict(set)
def postTweet(self, userId, tweetId):
self.tweetMap[userId].append([self.count, tweetId])
self.count -= 1
def getNewsFeed(self, userId):
res = []
minHeap = []
self.followMap[userId].add(userId)
for followeeId in self.followMap[userId]:
if followeeId in self.tweetMap:
index = len(self.tweetMap[followeeId]) - 1
count, tweetId = self.tweetMap[followeeId][index]
minHeap.append([count, tweetId, followeeId, index - 1])
heapq.heapify(minHeap)
while minHeap and len(res) < 10:
count, tweetId, followeeId, index = heapq.heappop(minHeap)
res.append(tweetId)
if index >= 0:
count, tweetId = self.tweetMap[followeeId][index]
heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1])
return res
def follow(self, followerId, followeeId):
self.followMap[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
if followeeId in self.followMap[followerId]: self.followMap[followerId].remove(followeeId)Код грубой силы (спойлер защищен)
Код грубой силы (спойлер защищен)
class TwitterBrute:
def __init__(self):
self.tweets = []
self.following = collections.defaultdict(set)
def postTweet(self, userId, tweetId):
self.tweets.append((userId, tweetId))
def getNewsFeed(self, userId):
res = []
for u, t in reversed(self.tweets):
if u == userId or u in self.following[userId]:
res.append(t)
if len(res) == 10: break
return res
def follow(self, followerId, followeeId):
self.following[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
if followeeId in self.following[followerId]: self.following[followerId].remove(followeeId)Algorithm Pattern Checklist
When dealing with Heap / Priority Queue data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
Standard Heap / Priority Queue problem properties apply.
Связанные вопросы
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Рекомендуемые ресурсы Python
Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.
Циклы Python
Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.
Как отсортировать список в Python
Узнайте, как сортировать список в Python с помощью метода sort() и функции sorted(). Ознакомьтесь с примерами пользовательской сортировки ключей и обратного порядка.
Шпаргалка по строковым методам Python
Полное справочное руководство по манипулированию строками в Python. Мастер форматирования, поиска, разделения, замены и проверки свойств строк.
Python против JavaScript: какой язык программирования лучше?
Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.