Quota-Based Storage Service Simulator with Snapshots
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate a command stream on a storage service with per-user quotas, ownership transfer, prefix-based top-n listing, and per-user snapshot and restore.
Quota-Based Storage Service Simulator
You are given a log of commands for a small in-memory storage service. Process the commands in order and return one result per command.
The function receives two lists of equal length. commands[i] is the name of a command, and payloads[i] is the list of arguments for it. Return a list results where results[i] is the outcome of command i. Use None for a "no result" outcome.
Model
- A file has a unique name (string) and a positive integer size. No two files can share a name, regardless of owner.
- Every file has exactly one owner.
- Every regular user has a remaining quota: the number of bytes they may still store. Adding a file reduces the owner's remaining quota by its size, and removing a file gives that size back to its current owner.
- A special owner called
"admin"exists from the start. Admin files are not subject to any quota, and admin has no quota to track. The"admin"identifier cannot be created, merged, backed up or restored, as described below. - Initially there are no files, no regular users and no backups.
Commands
-
add_user, payload[user_id, quota]- If
user_idis"admin"or a user with that id already exists, the result isFalse. - Otherwise create the user with remaining quota
quota. The new user has no backup. The result isTrue.
- If
-
add_file, payload[name, size]- Adds a file owned by
"admin". - If a file called
namealready exists, the result isFalse. Otherwise add it and the result isTrue.
- Adds a file owned by
-
add_file_by, payload[user_id, name, size]- The result is
Noneand nothing changes if any of these hold:user_idis"admin",user_idis not an existing user,- a file called
namealready exists, sizeis greater than the user's remaining quota.
- Otherwise the file is added with that user as owner, the user's remaining quota drops by
size, and the result is the new remaining quota. (A file whose size equals the remaining quota is allowed.)
- The result is
-
get_file_size, payload[name]- The result is the file's size, or
Noneif there is no such file.
- The result is the file's size, or
-
delete_file, payload[name]- If there is no such file, the result is
None. - Otherwise remove it and the result is its size. If its owner is a regular user, that size is added back to the owner's remaining quota. Deleting an admin file refunds nothing.
- If there is no such file, the result is
-
get_n_largest, payload[prefix, n]- Consider all files (of any owner) whose name starts with
prefix. An empty prefix matches every file. - Order them by size descending, breaking ties by name ascending (plain string comparison).
- The result is a list of at most
nstrings of the form"<name>(<size>)", taken from the front of that order. - If
n <= 0or nothing matches, the result is[].
- Consider all files (of any owner) whose name starts with
-
merge_user, payload[user_id_1, user_id_2]- The result is
Noneand nothing changes if the two ids are equal, if either is"admin", or if either is not an existing user. - Otherwise:
- every file owned by
user_id_2becomes owned byuser_id_1, user_id_2's remaining quota is added touser_id_1's remaining quota (file sizes themselves cause no change, since they were already counted),user_id_2is removed, together with any backup it had,- the result is
user_id_1's new remaining quota.
- every file owned by
- The result is
-
backup_user, payload[user_id]- If
user_idis"admin"or not an existing user, the result isNone. - Otherwise record a snapshot mapping each file name currently owned by the user to its size. This replaces any earlier snapshot of that user. The result is the number of files in the snapshot.
- If
-
restore_user, payload[user_id]- If
user_idis"admin"or not an existing user, the result isNone. - Otherwise do the following in order:
- Remove every file the user currently owns, refunding their sizes to the user's remaining quota. This happens even if the user has no snapshot.
- For each entry in the user's snapshot (if any), re-create the file for this user only if no file with that name exists at that moment. Each re-created file reduces the user's remaining quota by its size. No other quota check is made.
- The result is the number of files re-created (
0if there is no snapshot). Restoring does not delete the snapshot.
- If
You may assume every command name is one of the nine above and that payloads have the shape described.
Constraints
1 <= len(commands) == len(payloads) <= 10^5- User ids and file names are strings; sizes and quotas are integers, with sizes positive and quotas non-negative.
ninget_n_largestis an integer and may be zero or negative.- Results must match the rules above exactly, including
NoneversusFalseoutcomes.
Examples
Example 1
Input: simulate_storage(['add_user', 'add_file_by', 'add_file_by', 'get_file_size', 'get_n_largest', 'delete_file'], [['alice', 100], ['alice', 'docs/a.txt', 30], ['alice', 'docs/b.txt', 80], ['docs/a.txt'], ['docs/', 5], ['docs/a.txt']])
Output: [True, 70, None, 30, ['docs/a.txt(30)'], 30]
Example 2
Input: simulate_storage(['add_user', 'add_user', 'add_file_by', 'add_file_by', 'merge_user', 'get_n_largest'], [['u1', 100], ['u2', 50], ['u1', 'a', 20], ['u2', 'b', 30], ['u1', 'u2'], ['', 10]])
Output: [True, True, 80, 20, 100, ['b(30)', 'a(20)']]
Example 3
Input: simulate_storage(['add_user', 'add_file_by', 'backup_user', 'delete_file', 'add_file', 'restore_user', 'get_n_largest'], [['u', 100], ['u', 'report', 40], ['u'], ['report'], ['report', 10], ['u'], ['', 10]])
Output: [True, 60, 1, 40, True, 0, ['report(10)']]
Hints
Hint 1
Keep one master table from file name to (size, owner), plus a per-user set of owned names so merge, backup and restore do not need to scan every file.
Hint 2
Route every ownership change through two small helpers (attach a file to a user, detach a file from its owner) so the quota arithmetic is written once. Remember that admin files never touch any quota.
Hint 3
For listing, filter by startswith and sort with the key (-size, name). Handle n <= 0 explicitly.
Hint 4
Restore always clears the user's current files first, even with no snapshot, and only then re-creates snapshot files whose names are free. A removed or newly created user must not carry over an old snapshot.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a bookkeeping problem rather than an algorithmic one. The goal is to keep several views of the same state consistent while following each rule exactly.
Maintain four dictionaries:
| Structure | Meaning |
|---|---|
files | file name -> [size, owner], the single source of truth for what exists |
quotas | regular user -> remaining quota |
owned | user -> set of names they own, so per-user operations avoid a full scan |
snapshots | user -> {name: size} from the latest backup |
Admin is not stored in quotas or owned. Files owned by admin simply have the owner "admin", and all quota logic is skipped for them.
Command by command
add_user: reject"admin"and existing ids. A new user starts with an empty file set, and any stale snapshot under that id is dropped (it can exist only if the id was merged away earlier, but we clear it anyway).add_file: only a name-collision check, and the owner is"admin".add_file_by: reject admin, unknown users, existing names, and sizes above the remaining quota. All of these leave state untouched. Otherwise record the file, deduct the quota and return the new remaining quota.get_file_size: dictionary lookup.delete_file: pop the entry. If the current owner is a regular user, refund the size and drop the name from their set. Because merge rewrites the owner field, a merged file refunds the surviving user.get_n_largest: filter bystartswith, sort with the key(-size, name)(this encodes both size descending and name ascending), and slice the firstn. Forn <= 0return[].merge_user: validate the ids, then addu2's remaining quota tou1, retargetu2's files tou1, merge the name sets, and deleteu2along with its snapshot. File sizes are not charged again, because those bytes are already accounted for.backup_user: build a fresh{name: size}dictionary from the user's owned names, so later changes cannot alter it, and replace any earlier snapshot.restore_user: first remove all of the user's current files, refunding their sizes (this happens even without a snapshot). Then re-create each snapshot file whose name is currently unused, deducting its size, and count them. Names taken by other users are skipped.
Why it is correct
Two invariants hold after each command:
- A name is in
owned[u]exactly whenfiles[name]listsuas owner. - For each regular user,
remaining quota + total size of owned filesequals the total quota the user has accumulated through creation and merges.
Every command either leaves state unchanged (all failure paths check before mutating) or moves names and bytes between files, owned and quotas in matching amounts, so both invariants are preserved. Since the invariants hold and each command follows the written rule, the outputs match the specification. Restore never needs a quota check, because by the second invariant, deleting the user's current files and re-adding a subset of an earlier snapshot never exceeds what the user can hold.
Complexity
Let F be the number of files, k the files owned by a user involved in a command, and m the number of prefix matches.
add_user,add_file,add_file_by,get_file_size,delete_file: O(1).get_n_largest: O(F + m log m).merge_user: O(k of the merged-away user).backup_user: O(k).restore_user: O(k current + k in snapshot).
Space is O(F + total snapshot size). If prefix queries dominated, a sorted list of names with bisect or a trie would avoid scanning every file.
Reference solution
from typing import List
def simulate_storage(commands: List[str], payloads: List[List[object]]) -> List[object]:
quotas = {} # user -> remaining quota (regular users only)
files = {} # name -> [size, owner]
owned = {} # user -> set of owned file names
snapshots = {} # user -> {name: size}
results = []
for cmd, args in zip(commands, payloads):
if cmd == "add_user":
user_id, quota = args
if user_id == "admin" or user_id in quotas:
results.append(False)
else:
quotas[user_id] = quota
owned[user_id] = set()
snapshots.pop(user_id, None)
results.append(True)
elif cmd == "add_file":
name, size = args
if name in files:
results.append(False)
else:
files[name] = [size, "admin"]
results.append(True)
elif cmd == "add_file_by":
user_id, name, size = args
if (user_id == "admin" or user_id not in quotas
or name in files or size > quotas[user_id]):
results.append(None)
else:
files[name] = [size, user_id]
owned[user_id].add(name)
quotas[user_id] -= size
results.append(quotas[user_id])
elif cmd == "get_file_size":
name = args[0]
results.append(files[name][0] if name in files else None)
elif cmd == "delete_file":
name = args[0]
entry = files.pop(name, None)
if entry is None:
results.append(None)
else:
size, owner = entry
if owner != "admin":
owned[owner].remove(name)
quotas[owner] += size
results.append(size)
elif cmd == "get_n_largest":
prefix, n = args
if n <= 0:
results.append([])
else:
matches = [(entry[0], name) for name, entry in files.items()
if name.startswith(prefix)]
matches.sort(key=lambda item: (-item[0], item[1]))
results.append([f"{name}({size})" for size, name in matches[:n]])
elif cmd == "merge_user":
u1, u2 = args
if (u1 == u2 or u1 == "admin" or u2 == "admin"
or u1 not in quotas or u2 not in quotas):
results.append(None)
else:
quotas[u1] += quotas[u2]
for name in owned[u2]:
files[name][1] = u1
owned[u1].update(owned[u2])
del quotas[u2]
del owned[u2]
snapshots.pop(u2, None)
results.append(quotas[u1])
elif cmd == "backup_user":
user_id = args[0]
if user_id == "admin" or user_id not in quotas:
results.append(None)
else:
snap = {name: files[name][0] for name in owned[user_id]}
snapshots[user_id] = snap
results.append(len(snap))
elif cmd == "restore_user":
user_id = args[0]
if user_id == "admin" or user_id not in quotas:
results.append(None)
continue
for name in list(owned[user_id]):
size, _ = files.pop(name)
quotas[user_id] += size
owned[user_id].clear()
restored = 0
for name, size in snapshots.get(user_id, {}).items():
if name not in files:
files[name] = [size, user_id]
owned[user_id].add(name)
quotas[user_id] -= size
restored += 1
results.append(restored)
else:
raise ValueError(f"Unknown command: {cmd}")
return results