디자인 트위터
'Design Twitter' 문제에 대한 자세한 가이드 및 Python 구현입니다.
1. 배우다
'Design Twitter' 문제는 Heap/Priority Queue 섹션의 핵심 과제입니다.
이 구현은 Python의 쉬운 수준 논리에 중점을 둡니다.
우리는 제공되는 솔루션에서 기술적 정확성과 코드 가독성을 최우선으로 생각합니다.
2. Real-World Applications
3. Visual Intuition
Design Twitter의 논리 흐름을 시각화합니다.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Design Twitter의 문제 설명을 주의 깊게 읽어보세요.
2. Formulate brute force
간단한 반복 솔루션 초안을 작성합니다.
3. Identify inefficiency
중복 계산을 찾으십시오.
4. Optimize search path
해싱이나 정렬을 사용하여 프로세스 속도를 높입니다.
5. Final Implementation
생산 표준에 맞게 코드를 정리합니다.
문제 설명
사용자가 트윗을 게시하고, 다른 사용자를 팔로우/언팔로우하고, 사용자의 뉴스피드에서 가장 최근 트윗 10개를 볼 수 있는 간단한 버전의 트위터를 디자인하세요.
Twitter 클래스를 구현합니다.
- Twitter() 트위터 개체를 초기화합니다.
- postTweet(userId: int, tweetId: int) 사용자 userId의 tweetId ID로 새 트윗을 작성합니다.
- getNewsFeed(userId: int) -> List[int] 사용자의 뉴스피드에서 가장 최근 트윗 ID 10개를 검색합니다.
- follow(followerId: int, followeeId: int) ID가 followerId인 사용자가 ID가 followeeId인 사용자를 팔로우하기 시작했습니다.
- unfollow(followerId: int, followeeId: int) ID가 followerId인 사용자가 ID가 followeeId인 사용자를 언팔로우하기 시작했습니다.
입력은 작업 및 인수 목록입니다. 결과 목록을 반환하는 twitter(operations: list, arguments: list) -> list 함수를 구현합니다(생성자/postTweet/follow/unfollow의 경우 없음, getNewsFeed의 경우 List[int]).
- •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
- 빈 입력 구조
- 단일 요소 입력
- 큰 수치 범위
해결할 준비가 되셨나요?
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
표준 힙/우선순위 큐 문제 속성이 적용됩니다.
관련 질문
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에서 목록을 정렬하는 방법(오름차순 및 내림차순)
sort() 메서드와 sorted() 함수를 사용하여 Python에서 목록을 정렬하는 방법을 알아보세요. 사용자 정의 키 정렬 및 역순 예시를 살펴보세요.
Python 문자열 메서드 치트 시트
Python 문자열 조작에 대한 완전한 참조 가이드입니다. 문자열 속성의 서식 지정, 검색, 분할, 바꾸기 및 확인을 마스터합니다.
Python 대 JavaScript: 어떤 프로그래밍 언어가 가장 좋나요?
Python과 JavaScript를 포괄적으로 비교합니다. 구문 차이점, 성능, 사용 사례(백엔드와 프런트엔드) 및 코딩 예제를 살펴보세요.