Thiết kế Twitter
Hướng dẫn chi tiết và cách triển khai Python cho bài toán 'Thiết kế Twitter'.
1. Tìm hiểu
Bài toán “Thiết kế Twitter” là một thách thức chính trong phần Heap/hàng đợi ưu tiên.
Việc triển khai này tập trung vào logic cấp độ dễ trong Python.
Chúng tôi ưu tiên độ chính xác về mặt kỹ thuật và khả năng đọc mã trong các giải pháp được cung cấp của chúng tôi.
2. Real-World Applications
3. Visual Intuition
Trực quan hóa luồng logic cho Thiết kế Twitter.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Đọc kỹ báo cáo vấn đề dành cho Thiết kế Twitter.
2. Formulate brute force
Soạn thảo một giải pháp lặp lại đơn giản.
3. Identify inefficiency
Tìm các phép tính dư thừa.
4. Optimize search path
Sử dụng hàm băm hoặc sắp xếp để tăng tốc quá trình.
5. Final Implementation
Làm sạch mã cho tiêu chuẩn sản xuất.
Tuyên bố vấn đề
Thiết kế một phiên bản Twitter đơn giản hóa nơi người dùng có thể đăng tweet, theo dõi/hủy theo dõi người dùng khác và có thể xem 10 tweet gần đây nhất trong nguồn cấp tin tức của người dùng.
Triển khai lớp Twitter:
- Twitter() Khởi tạo đối tượng twitter của bạn.
- postTweet(userId: int, tweetId: int) Soạn một tweet mới có ID tweetId bởi người dùng userId.
- getNewsFeed(userId: int) -> List[int] Truy xuất 10 ID tweet gần đây nhất trong nguồn cấp tin tức của người dùng.
- follow(followerId: int, followeeId: int) Người dùng có ID followerId đã bắt đầu theo dõi người dùng có ID followeeId.
- unfollow(followerId: int, followeeId: int) Người dùng có ID followerId đã bắt đầu hủy theo dõi người dùng có ID followeeId.
Đầu vào là danh sách các phép toán và đối số. Triển khai hàm twitter(operations: list, arguments: list) -> list trả về danh sách kết quả (Không có kết quả nào cho hàm tạo/postTweet/follow/unfollow và List[int] cho 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
Ví dụ
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
- Cấu trúc đầu vào trống
- Đầu vào phần tử đơn
- Giới hạn số lớn
Sẵn sàng để giải quyết?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Thông tin chi tiết và biến thể của cuộc phỏng vấn
Phân tích độ phức tạp
Tại sao thời gian: Directly evaluates all possibilities.
Tại sao không gian: Uses standard local memory.
Tại sao thời gian: Optimized paths reduce total operations.
Tại sao không gian: May trade memory for speed.
Mã Python giải pháp tối ưu hóa
Mã Python giải pháp tối ưu hóa
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)Mã Brute Force (Bảo vệ spoiler)
Mã Brute Force (Bảo vệ spoiler)
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
Áp dụng các thuộc tính vấn đề về Heap/Hàng ưu tiên tiêu chuẩn.
Câu hỏi liên quan
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Tài nguyên Python được đề xuất
Mở rộng kiến thức của bạn với các hướng dẫn tương tác, bảng ghi chú và so sánh mã có liên quan.
Vòng lặp Python
Tìm hiểu cách sử dụng vòng lặp Python để lặp lại dữ liệu. Nắm vững các phương pháp hay nhất về vòng lặp for, while, ngắt, tiếp tục và lặp bằng các ví dụ tương tác.
Cách sắp xếp danh sách trong Python
Tìm hiểu cách sắp xếp danh sách trong Python bằng phương thức Sort() và hàm Sort(). Khám phá các ví dụ về sắp xếp khóa tùy chỉnh và thứ tự đảo ngược.
Bảng cheat phương thức chuỗi Python
Hướng dẫn tham khảo đầy đủ về thao tác chuỗi Python. Làm chủ định dạng, tìm kiếm, phân tách, thay thế và kiểm tra thuộc tính chuỗi.
Python vs JavaScript: Ngôn ngữ lập trình nào tốt nhất?
So sánh toàn diện giữa Python và JavaScript. Khám phá sự khác biệt về cú pháp, hiệu suất, trường hợp sử dụng (phụ trợ so với giao diện người dùng) và các ví dụ về mã hóa.