Design a File Sharing System Problem
Description
LeetCode Problem 1500.
We will use a file-sharing system to share a very large file which consists of m small chunks with IDs from 1 to m.
When users join the system, the system should assign a unique ID to them. The unique ID should be used once for each user, but when a user leaves the system, the ID can be reused again.
Users can request a certain chunk of the file, the system should return a list of IDs of all the users who own this chunk. If the user receives a non-empty list of IDs, they receive the requested chunk successfully.
Implement the FileSharing class:
FileSharing(int m)Initializes the object with a file ofmchunks.int join(int[] ownedChunks): A new user joined the system owning some chunks of the file, the system should assign an id to the user which is the smallest positive integer not taken by any other user. Return the assigned id.void leave(int userID): The user withuserIDwill leave the system, you cannot take file chunks from them anymore.int[] request(int userID, int chunkID): The useruserIDrequested the file chunk withchunkID. Return a list of the IDs of all users that own this chunk sorted in ascending order.
Example:
Input:
["FileSharing","join","join","join","request","request","leave","request","leave","join"]
[[4],[[1,2]],[[2,3]],[[4]],[1,3],[2,2],[1],[2,1],[2],[[]]]
Output:
[null,1,2,3,[2],[1,2],null,[],null,1]
Explanation:
FileSharing fileSharing = new FileSharing(4); // We use the system to share a file of 4 chunks.
fileSharing.join([1, 2]); // A user who has chunks [1,2] joined the system, assign id = 1 to them and return 1.
fileSharing.join([2, 3]); // A user who has chunks [2,3] joined the system, assign id = 2 to them and return 2.
fileSharing.join([4]); // A user who has chunk [4] joined the system, assign id = 3 to them and return 3.
fileSharing.request(1, 3); // The user with id = 1 requested the third file chunk, as only the user with id = 2 has the file, return [2] . Notice that user 1 now has chunks [1,2,3].
fileSharing.request(2, 2); // The user with id = 2 requested the second file chunk, users with ids [1,2] have this chunk, thus we return [1,2].
fileSharing.leave(1); // The user with id = 1 left the system, all the file chunks with them are no longer available for other users.
fileSharing.request(2, 1); // The user with id = 2 requested the first file chunk, no one in the system has this chunk, we return empty list [].
fileSharing.leave(2); // The user with id = 2 left the system.
fileSharing.join([]); // A user who doesn't have any chunks joined the system, assign id = 1 to them and return 1. Notice that ids 1 and 2 are free and we can reuse them.
Constraints:
1 <= m <= 10^50 <= ownedChunks.length <= min(100, m)1 <= ownedChunks[i] <= m- Values of
ownedChunksare unique. 1 <= chunkID <= muserIDis guaranteed to be a user in the system if you assign the IDs correctly.- At most
10^4calls will be made tojoin,leaveandrequest. - Each call to
leavewill have a matching call forjoin.
Follow-up:
- What happens if the system identifies the user by their IP address instead of their unique ID and users disconnect and connect from the system with the same IP?
- If the users in the system join and leave the system frequently without requesting any chunks, will your solution still be efficient?
- If all users join the system one time, request all files, and then leave, will your solution still be efficient?
- If the system will be used to share
nfiles where theithfile consists ofm[i], what are the changes you have to make?
Solution
Approach: Min-Heap of Free IDs and Owner Sets
Two things need care: handing out the smallest free ID, and finding who owns a chunk.
IDs. Keep nextId, the smallest ID never handed out, and a min-heap of IDs given back by users who left. join takes the heap's smallest ID if there is one, and otherwise nextId (then increments it). Every ID below nextId is either in use or in the heap, so this is always the smallest positive integer not taken.
Chunks. Keep two maps that mirror each other:
chunksOf[user]: the set of chunks a user owns.owners[chunk]: the set of users who own a chunk.
join fills both from ownedChunks. leave removes the user from owners[c] for each chunk c they own, deletes chunksOf[user], and pushes the ID onto the heap. request(userID, chunkID) returns the owners of chunkID in ascending order; if that list is not empty, the request succeeded and the requester now owns the chunk too, so add it to both maps. Take the list before adding the requester: the answer lists the users who owned the chunk at the time of the request.
In Java and C++ a sorted set (TreeSet, set) gives the owners in order directly; in the other languages we sort the owners when returning them.
Complexity: join is O(c + log u) and leave is O(c + log u), where c is the number of chunks the user owns and u the number of IDs handed out; request is O(r log r) to list r owners (O(r) with a sorted set). Space is O(u + total chunks owned).
import heapq
from collections import defaultdict
class FileSharing:
def __init__(self, m: int):
self.next_id = 1 # smallest id never handed out
self.free = [] # min-heap of ids given back by users who left
self.chunks_of = {} # user id -> set of chunks they own
self.owners = defaultdict(set) # chunk id -> set of users who own it
def join(self, ownedChunks: List[int]) -> int:
if self.free:
user = heapq.heappop(self.free)
else:
user = self.next_id
self.next_id += 1
self.chunks_of[user] = set(ownedChunks)
for c in ownedChunks:
self.owners[c].add(user)
return user
def leave(self, userID: int) -> None:
for c in self.chunks_of.pop(userID):
self.owners[c].discard(userID)
heapq.heappush(self.free, userID)
def request(self, userID: int, chunkID: int) -> List[int]:
result = sorted(self.owners[chunkID])
if result: # the request succeeded, so the user now owns the chunk too
self.chunks_of[userID].add(chunkID)
self.owners[chunkID].add(userID)
return result