LeetCode 1500: Design a File Sharing System
Problem Description
Explanation:
To design a file sharing system, we can implement a system that supports the following operations:
join(int[] ownedChunks)
: A new user joins the system with the given list of owned file chunks.leave(int userID)
: A user leaves the system.request(int userID, int chunkID)
: A user requests a chunk with a specific ID.share(int userID, int chunkID)
: A user shares a chunk with another user.
We can use a combination of data structures such as HashMaps, Sets, and Lists to efficiently implement the file sharing system.
Algorithm:
- Maintain a HashMap where the key is the user ID and the value is a Set of chunks owned by that user.
- To join a new user, add an entry to the HashMap with the user ID and the Set of owned chunks.
- To leave a user, remove the entry from the HashMap.
- To request a chunk, iterate through all users and check if any user owns the requested chunk. If found, return the user ID.
- To share a chunk, add the chunk to the Set of owned chunks for the target user.
Time Complexity:
join()
: O(1)leave()
: O(1)request()
: O(n) where n is the number of usersshare()
: O(1)
Space Complexity:
- O(n) where n is the total number of users and chunks in the system.
: :
Solutions
import java.util.*;
class FileSharingSystem {
Map<Integer, Set<Integer>> userChunks;
public FileSharingSystem() {
userChunks = new HashMap<>();
}
public void join(int[] ownedChunks) {
Set<Integer> chunks = new HashSet<>();
for (int chunk : ownedChunks) {
chunks.add(chunk);
}
userChunks.put(userChunks.size() + 1, chunks);
}
public void leave(int userID) {
userChunks.remove(userID);
}
public List<Integer> request(int userID, int chunkID) {
List<Integer> res = new ArrayList<>();
for (Map.Entry<Integer, Set<Integer>> entry : userChunks.entrySet()) {
if (entry.getValue().contains(chunkID)) {
res.add(entry.getKey());
}
}
return res;
}
public void share(int userID, int chunkID) {
userChunks.get(userID).add(chunkID);
}
}
Loading editor...