Design a File Sharing System - Problem
Design 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.
Input & Output
Example 1 — Basic Operations
$
Input:
FileSharing(4), join([1,2]), join([2,3]), request(1,2), leave(1), join([4])
›
Output:
[null,1,2,[1,2],null,1]
💡 Note:
Initialize with 4 chunks. User 1 joins with chunks [1,2], gets ID 1. User 2 joins with chunks [2,3], gets ID 2. User 1 requests chunk 2, returns [1,2] (both users have it). User 1 leaves, ID 1 becomes available. New user joins with chunk [4], gets reused ID 1.
Example 2 — ID Reuse
$
Input:
FileSharing(3), join([1]), join([2]), leave(1), join([3])
›
Output:
[null,1,2,null,1]
💡 Note:
Two users join and get IDs 1,2. User 1 leaves, making ID 1 available. Next user gets the smallest available ID which is 1 (reused).
Example 3 — Empty Request
$
Input:
FileSharing(2), join([1]), request(1,2)
›
Output:
[null,1,[]]
💡 Note:
User 1 has chunk 1 but requests chunk 2. Since no one owns chunk 2, return empty list and user doesn't get the chunk.
Constraints
- 1 ≤ m ≤ 105
- 0 ≤ ownedChunks.length ≤ m
- 1 ≤ ownedChunks[i] ≤ m
- Values of ownedChunks are unique
- 1 ≤ chunkID ≤ m
- userID is guaranteed to be a user in the system if you assign the ID to them
- At most 104 calls will be made to join, leave and request
Visualization
Tap to expand
Understanding the Visualization
1
System Setup
Initialize with m chunks and prepare for user management
2
User Operations
Handle join (assign IDs), leave (free IDs), and request (find owners)
3
Efficient Sharing
Return sorted list of users who own requested chunks
Key Takeaway
🎯 Key Insight: Use hash maps for bidirectional lookups and min-heap for optimal ID management to achieve fast operations in a scalable file sharing system
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code