Build an In-Memory File Store with Quotas and Backups
Data Structure DesignModel answerLast updated
Implement an in-memory file store with prefix top-N queries, per-user quotas, user merging, and per-user backup and restore that never disturb other users.
Task
Implement a class that simulates a simple in-memory file store. The requirements arrive in stages, and every stage must keep the earlier ones working. Explain your data model, the invariants you maintain, and the complexity of each operation, then write the code.
Stage 1: Basic files
add_file(name, size)stores a file with a globally unique name.get_file_size(name)returns the size of a stored file.delete_file(name)removes a file and reports what was removed.
Stage 2: Prefix ranking
get_n_largest(prefix, n)returns thenbiggest files whose names start withprefix.
Stage 3: Users and quotas
add_user(user_id, capacity)creates a user with a storage limit.add_file_by(user_id, name, size)stores a file on behalf of that user, but only if it fits inside the user's remaining capacity.- Files added through Stage 1 belong to a built-in user with unlimited capacity.
Stage 4: Merging users
merge_user(user_id1, user_id2)moves all files and the total capacity of the second user into the first, and then removes the second user.
Stage 5: Backup and restore
backup_user(user_id)saves a snapshot of that user's current files.restore_user(user_id)returns that user's files to the snapshot state.- Backups and restores must never change another user's files or any user's capacity.
What to specify
Since the specification leaves details open, state your return-value conventions explicitly. A reasonable set:
- Operations that fail (duplicate name, unknown user, not enough room) return a failure value such as
FalseorNone. get_n_largestreturns strings of the formname(size), ordered by size descending and then by name ascending.add_file_byreturns the user's remaining capacity on success.merge_userreturns the remaining capacity of the surviving user, and fails if the two ids are equal or either is unknown.backup_userandrestore_userreturn the number of files saved or restored.
Questions to address
- Which data structures give O(1) existence checks and O(1) capacity checks?
- How do you guarantee that merge and restore cannot corrupt usage accounting?
- What should restore do when a file name in the snapshot has since been taken by someone else?
- How would you speed up prefix queries if they dominated the workload?
Hints
Hint 1
Keep one global map from file name to (owner, size), since names are unique across all users, and give each user a counter of used space that you update incrementally.
Hint 2
Funnel every mutation through two small helpers (one to insert, one to remove) that update the global map, the owner's file set, and the owner's used counter together; merge and restore can then be built from them.
Hint 3
A snapshot must be an independent copy of name-to-size. On restore, remove only the current user's files, then re-add snapshot files whose names are still free, and leave capacity untouched.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a progressive implementation problem, so the goal is a small set of data structures and invariants that stay correct as each stage is added.
Contract (state this first)
| Method | Result |
|---|---|
add_file | True if added, False if the name exists. Owner is an unlimited admin user. |
get_file_size | Size, or None if missing. |
delete_file | Size of the deleted file, or None. Frees the owner's capacity. |
get_n_largest | Up to n strings name(size), size descending, then name ascending. |
add_user | False if the user exists. |
add_file_by | Remaining capacity, or None if user unknown, name taken, or file does not fit. |
merge_user | Remaining capacity of user 1, or None if ids are equal or unknown. |
backup_user / restore_user | File count, or None for an unknown user. |
Data model
files: name -> (owner, size)for O(1) global duplicate checks.users: id -> {capacity, used, files}wherefilesis a set of names andusedis maintained incrementally, so the capacity test is O(1).backups: id -> {name: size}is a copy taken at backup time, so later changes cannot leak into it.
Invariants
- A name is in
fileswith owneruexactly when it is inusers[u].files. users[u].usedequals the sum of that user's file sizes and never exceedscapacity.
All writes go through _put and _remove, which update the three structures together. Because nothing else mutates state, the invariants are easy to argue.
Why each stage preserves them
- Add and delete: handled by the helpers. A fit check uses
used + size <= capacity, so a file that exactly fills the quota is allowed. - Merge: reassign each file of user 2 to user 1 and add capacities. Since
used1 + used2 <= cap1 + cap2, no check is needed. Then delete user 2 and its backup. Reject equal ids, unknown ids, and the admin user. - Restore: remove only this user's current files, then re-add snapshot entries whose names are not owned by someone else. Other users are untouched. Capacity never decreases (merges only increase it), and the snapshot fit when taken, so a subset of it still fits. With no backup, restore simply clears the user's files.
Complexity
F is the total file count, k the user's file count, b the snapshot size.
| Operation | Time |
|---|---|
| add/get/delete file, add user, add file by user | O(1) |
get_n_largest | O(F + m log n) using a bounded heap over m matches |
merge_user | O(k of user 2) |
backup_user | O(k) |
restore_user | O(k + b) |
Space is O(F + total backed-up files).
If prefix queries dominate, keep a trie whose nodes hold sorted sets of (-size, name), or keep a sorted list of names and binary-search the prefix range. Mention this but do not build it unless asked; the extra bookkeeping on every write is usually not worth it here.
Code
import heapq
from typing import Dict, List, Optional, Tuple
class CloudStorage:
ADMIN = "admin"
def __init__(self) -> None:
self.files: Dict[str, Tuple[str, int]] = {}
self.users: Dict[str, dict] = {
self.ADMIN: {"capacity": float("inf"), "used": 0, "files": set()}
}
self.backups: Dict[str, Dict[str, int]] = {}
def _put(self, owner: str, name: str, size: int) -> None:
self.files[name] = (owner, size)
u = self.users[owner]
u["files"].add(name)
u["used"] += size
def _remove(self, name: str) -> int:
owner, size = self.files.pop(name)
u = self.users[owner]
u["files"].discard(name)
u["used"] -= size
return size
def add_file(self, name: str, size: int) -> bool:
if name in self.files:
return False
self._put(self.ADMIN, name, size)
return True
def get_file_size(self, name: str) -> Optional[int]:
e = self.files.get(name)
return e[1] if e else None
def delete_file(self, name: str) -> Optional[int]:
return self._remove(name) if name in self.files else None
def get_n_largest(self, prefix: str, n: int) -> List[str]:
if n <= 0:
return []
m = ((-s, nm) for nm, (_, s) in self.files.items() if nm.startswith(prefix))
return [f"{nm}({-neg})" for neg, nm in heapq.nsmallest(n, m)]
def add_user(self, user_id: str, capacity: int) -> bool:
if user_id in self.users:
return False
self.users[user_id] = {"capacity": capacity, "used": 0, "files": set()}
return True
def add_file_by(self, user_id: str, name: str, size: int) -> Optional[int]:
u = self.users.get(user_id)
if u is None or name in self.files or u["used"] + size > u["capacity"]:
return None
self._put(user_id, name, size)
return u["capacity"] - u["used"]
def merge_user(self, id1: str, id2: str) -> Optional[int]:
if id1 == id2 or id1 not in self.users or id2 not in self.users:
return None
if self.ADMIN in (id1, id2):
return None
u1, u2 = self.users[id1], self.users[id2]
for name in list(u2["files"]):
size = self._remove(name)
self._put(id1, name, size)
u1["capacity"] += u2["capacity"]
del self.users[id2]
self.backups.pop(id2, None)
return u1["capacity"] - u1["used"]
def backup_user(self, user_id: str) -> Optional[int]:
u = self.users.get(user_id)
if u is None:
return None
self.backups[user_id] = {n: self.files[n][1] for n in u["files"]}
return len(self.backups[user_id])
def restore_user(self, user_id: str) -> Optional[int]:
u = self.users.get(user_id)
if u is None:
return None
for name in list(u["files"]):
self._remove(name)
count = 0
for name, size in self.backups.get(user_id, {}).items():
if name not in self.files:
self._put(user_id, name, size)
count += 1
return count
Edge cases and common mistakes
- Duplicate names are rejected even when another user owns the name.
nlarger than the number of matches returns all matches; an empty prefix matches everything; ties break by name.- Storing a reference to the live file set as the backup, instead of a copy, so later edits corrupt the snapshot.
- Forgetting to decrease
usedon delete, or to move usage when merging. - Rolling capacity back on restore, or overwriting a name now owned by another user.
- Using
<instead of<=in the capacity check. - Taking a second backup should replace the first, not accumulate.
- Sorting the whole file list for every prefix query when a bounded heap is enough.