[LeetCode] Design a File Sharing System

1500. Design a File Sharing System

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 of m chunks.
  • 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 with userID will leave the system, you cannot take file chunks from them anymore.
  • int[] request(int userID, int chunkID): The user userID requested the file chunk with chunkID. Return a list of the IDs of all users that own this chunk sorted in ascending order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class FileSharing {
vector<set<int>> joins;
unordered_map<int, unordered_set<int>> own;
int id = 1;
priority_queue<int, vector<int>, greater<int>> q;
public:
FileSharing(int m) {
joins = vector<set<int>>(m + 1);
}

int join(vector<int> ownedChunks) {
int userId;
if(!q.empty()) {
userId = q.top(); q.pop();
} else userId = id++;
own[userId] = unordered_set<int>(begin(ownedChunks), end(ownedChunks));
for(auto& o : ownedChunks)
joins[o].insert(userId);
return userId;
}

void leave(int userID) {
for(auto& o : own[userID])
joins[o].erase(userID);
own.erase(userID);
q.push(userID);
}

vector<int> request(int userID, int chunkID) {
vector<int> res = vector<int>(begin(joins[chunkID]), end(joins[chunkID]));
if(!own[userID].count(chunkID) and !res.empty()) {
joins[chunkID].insert(userID);
own[userID].insert(chunkID);
}
return res;
}
};

/**
* Your FileSharing object will be instantiated and called as such:
* FileSharing* obj = new FileSharing(m);
* int param_1 = obj->join(ownedChunks);
* obj->leave(userID);
* vector<int> param_3 = obj->request(userID,chunkID);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/18/PS/LeetCode/design-a-file-sharing-system/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.