- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 35 lines of Python from the credited upstream file 1500.py.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from sortedcontainers import SortedSet2 3 4class FileSharing:5 def __init__(self, m: int):6 self.userToChunks: dict[int, SortedSet[int]] = {}7 self.chunkToUsers: dict[int, SortedSet[int]] = {}8 self.availableUserIds: list[int] = []9 10 def join(self, ownedChunks: list[int]) -> int:11 userId = (heapq.heappop(self.availableUserIds) if self.availableUserIds12 else len(self.userToChunks) + 1)13 self.userToChunks[userId] = SortedSet(ownedChunks)14 for chunk in ownedChunks:15 self.chunkToUsers.setdefault(chunk, SortedSet()).add(userId)16 return userId17 18 def leave(self, userID: int) -> None:19 if userID not in self.userToChunks:20 return21 for chunk in self.userToChunks[userID]:22 self.chunkToUsers[chunk].discard(userID)23 if not self.chunkToUsers[chunk]:24 del self.chunkToUsers[chunk]25 del self.userToChunks[userID]26 heapq.heappush(self.availableUserIds, userID)27 28 def request(self, userID: int, chunkID: int) -> list[int]:29 if chunkID not in self.chunkToUsers:30 return []31 userIds = list(self.chunkToUsers[chunkID])32 self.userToChunks[userID].add(chunkID)33 self.chunkToUsers[chunkID].add(userID)34 return userIds35