Multi-User File System with Snapshots and Account Consolidation
Data Structure DesignAuto-graded · 13 test casesLast updated
Build an in-memory file storage system with per-user quotas, global file uniqueness, ranked retrieval, account merging, and atomic snapshot restore.
Build an in-memory file storage system that tracks users, enforces storage quotas, and supports snapshots with atomic restore operations.
Implement a function file_system_operations(operations: List[str], arguments: List[List]) -> List that processes a sequence of operations and returns their results.
The system supports these operations:
add_user: ["add_user", [user_id, capacity]]
Creates a user account with the specified storage capacity in bytes. Returns True if successful. Returns False if user_id already exists or capacity < 1.
add_file: ["add_file", [user_id, file_name, file_size]]
Adds a file to the user's storage. File names must be globally unique across all users. Returns True if successful. Returns False if:
user_iddoes not existfile_size < 1file_namealready exists anywhere in the system- Adding the file would exceed the user's capacity (current usage +
file_size>capacity)
get_largest_files: ["get_largest_files", [user_id, k]]
Returns up to k file names owned by user_id, ordered by size (largest first). Ties are broken alphabetically in ascending order. Returns an empty list if user_id does not exist or has no files.
merge_accounts: ["merge_accounts", [target_user_id, source_user_id]]
Consolidates two accounts:
- All files from
source_user_idare transferred totarget_user_id target_user_id's capacity increases bysource_user_id's capacitysource_user_idand its snapshot (if any) are permanently deleted- Returns
Falseiftarget_user_id == source_user_idor either user does not exist - Returns
Trueon success
backup_user: ["backup_user", [user_id]]
Creates a snapshot of all files currently owned by user_id. Overwrites any previous snapshot for this user. Returns False if user_id does not exist, otherwise True.
restore_user: ["restore_user", [user_id]]
Restores files from the user's most recent snapshot. This operation is atomic (all-or-nothing):
- Returns
Falseifuser_iddoes not exist or has no snapshot - Returns
Falseif any file in the snapshot is currently owned by a different user - Returns
Falseif the snapshot's total size exceeds the user's current capacity - If all checks pass: deletes all current files owned by
user_id, restores all snapshot files, and returnsTrue - If any check fails: no changes are made to the system
Constraints
user_idandfile_nameare non-empty alphanumeric strings1 <= capacity, file_size <= 10^91 <= k <= 10^3- Total operations <= 5 × 10^4
Examples
Example 1
Input: file_system_operations(['add_user', 'add_user', 'add_file', 'add_file', 'add_file', 'backup_user', 'add_file', 'get_largest_files', 'restore_user', 'get_largest_files'], [['alice', 100], ['bob', 50], ['alice', 'a.txt', 40], ['alice', 'b.txt', 30], ['alice', 'c.txt', 40], ['alice'], ['alice', 'd.txt', 20], ['alice', 2], ['alice'], ['alice', 5]])
Output: [True, True, True, True, False, True, True, ['a.txt', 'b.txt'], True, ['a.txt', 'b.txt']]
Hints
Hint 1
Use three hash maps: one for user data (capacity and files), one for global file ownership, and one for snapshots.
Hint 2
For restore_user, validate all preconditions before making any changes. Only mutate state after confirming the operation is valid.
Hint 3
When merging accounts, remember to update the global ownership map and delete the source user's snapshot.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The system maintains three dictionaries to track state:
- User data: Maps each user ID to a pair
[capacity, files_dict]wherefiles_dictmaps file names to sizes - File ownership: Maps each file name globally to its owner, ensuring uniqueness across all users
- Snapshots: Maps each user ID to a copy of their files dictionary at backup time
Each operation maps cleanly onto these structures:
- add_user: Reject if the user already exists, otherwise initialize with empty files
- add_file: Check user existence, global name uniqueness, and whether adding this file would exceed capacity (current total + new size > limit)
- get_largest_files: Sort the user's files by descending size, then ascending name for ties, and take the first k entries
- merge_accounts: Transfer all source files to target, update global ownership, sum capacities, and delete the source user and their snapshot
- backup_user: Store a shallow copy of the user's current files dictionary
- restore_user: This is the critical operation requiring careful validation
Why restore_user Is Atomic
The restore operation validates everything before touching any state:
- User exists and has a snapshot
- Snapshot's total size fits within user's current capacity (which may have changed via merges)
- No file in the snapshot is owned by another user (files owned by this user or not owned at all are fine)
Only after all checks pass do we mutate:
- Remove current files from global ownership
- Register snapshot files to this user
- Replace user's files with a fresh copy of the snapshot
The copy is essential—without it, subsequent file additions would corrupt the snapshot. Since we validate completely upfront, no rollback logic is needed. This is the key insight: check everything, then act.
Complexity
Let F = number of files a user owns, S = snapshot size:
- add_user: O(1)
- add_file: O(F) due to summing current usage (could optimize to O(1) with a running total)
- get_largest_files: O(F log F) for sorting
- merge_accounts: O(F_source) to transfer files
- backup_user: O(F) to copy files
- restore_user: O(F + S) to validate and restore
Space: O(total files + total snapshot entries)
With up to 50,000 operations, this scales comfortably.
Solution
from typing import List
def file_system_operations(operations: List[str], arguments: List[List]) -> List:
user_data = {} # user_id -> [capacity, {file_name: size}]
file_owners = {} # file_name -> user_id (global uniqueness)
snapshots = {} # user_id -> {file_name: size}
results = []
for op, args in zip(operations, arguments):
if op == "add_user":
user_id, capacity = args
if user_id in user_data:
results.append(False)
else:
user_data[user_id] = [capacity, {}]
results.append(True)
elif op == "add_file":
user_id, file_name, file_size = args
if (user_id not in user_data or file_name in file_owners or
sum(user_data[user_id][1].values()) + file_size > user_data[user_id][0]):
results.append(False)
else:
user_data[user_id][1][file_name] = file_size
file_owners[file_name] = user_id
results.append(True)
elif op == "get_largest_files":
user_id, k = args
if user_id not in user_data:
results.append([])
else:
files = user_data[user_id][1]
sorted_files = sorted(files.items(), key=lambda x: (-x[1], x[0]))
results.append([name for name, _ in sorted_files[:k]])
elif op == "merge_accounts":
target_user_id, source_user_id = args
if (target_user_id == source_user_id or
target_user_id not in user_data or
source_user_id not in user_data):
results.append(False)
else:
target_cap, target_files = user_data[target_user_id]
source_cap, source_files = user_data[source_user_id]
target_files.update(source_files)
for name in source_files:
file_owners[name] = target_user_id
user_data[target_user_id] = [target_cap + source_cap, target_files]
del user_data[source_user_id]
snapshots.pop(source_user_id, None)
results.append(True)
elif op == "backup_user":
user_id = args[0]
if user_id not in user_data:
results.append(False)
else:
snapshots[user_id] = user_data[user_id][1].copy()
results.append(True)
elif op == "restore_user":
user_id = args[0]
if user_id not in user_data or user_id not in snapshots:
results.append(False)
continue
snapshot = snapshots[user_id]
current_files = user_data[user_id][1]
# Validate before making changes
if (sum(snapshot.values()) > user_data[user_id][0] or
any(name in file_owners and file_owners[name] != user_id
for name in snapshot)):
results.append(False)
continue
# All checks passed - perform atomic restore
for name in current_files:
del file_owners[name]
for name in snapshot:
file_owners[name] = user_id
user_data[user_id][1] = snapshot.copy()
results.append(True)
return results