Quota-Limited Storage Simulator with Staging and Snapshots
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a per-user file store with staged uploads, quota checks, ranked prefix queries, and atomic snapshot restores under two conflict policies.
Quota-Limited Storage Simulator
You are simulating a storage backend shared by many users. Each user has a staging area (pending uploads) and a committed area (stored files). Every user may hold at most capacity bytes of committed files at any time. Files are identified by a path string and have a positive integer size.
Write a function that replays a sequence of operations and returns the result of each one, in order.
Input
capacity: the byte limit for each user's committed files.operations: a list of operation names.arguments: a list of the same length.arguments[i]is the list of arguments foroperations[i].
Initially nothing is staged, nothing is committed, and no snapshots exist.
Operations
"stage_file" with arguments [user_id, path, size]
Put path into the user's staging area with the given size. If path is already staged for that user, its staged size is replaced.
Imagine committing everything staged for that user (including this new entry). Staged entries replace committed entries with the same path. If the resulting committed total would exceed capacity, do nothing and return False. Otherwise record the staged file and return True. A failed call leaves the previous staged size, if any, unchanged.
"commit" with arguments [user_id]
Move every staged file of that user into their committed files, replacing committed files with the same path. Then empty that user's staging area. Return the number of staged paths that were merged (a path that replaced an existing committed file still counts). If nothing is staged, return 0. Commit does not re-check the capacity.
"top_k_by_prefix" with arguments [user_id, prefix, k]
Consider only the user's committed files whose path starts with prefix. Return a list of at most k paths, ordered by size descending, with ties broken by path in ascending lexicographic order. If fewer than k files match (or the user has none), return all matches (possibly []).
"backup" with arguments [snapshot_id]
Save a frozen copy of every user's committed files at this moment. If snapshot_id already exists, return False and change nothing. Otherwise store the copy and return True. Later changes never affect a stored snapshot.
"restore" with arguments [snapshot_id, conflict_strategy]
Rebuild the committed files from a snapshot. Staging areas are never touched.
Return False without changes if snapshot_id is unknown, or if conflict_strategy is not one of the two valid values below (an invalid strategy fails even when the snapshot exists).
"overwrite": the committed files of all users become exactly the snapshot's. Users not present in the snapshot end up with no committed files."keep_newer": start from the current committed files. For every file in the snapshot, add it if that user does not currently have that path. If the user has it, keep whichever version has the strictly larger size; on a tie keep the current version.
If, in the resulting state, any user's committed total exceeds capacity, abort the whole restore: change nothing and return False. Otherwise apply the result and return True.
Output
A list with one entry per operation, in order: a bool for stage_file, backup, and restore; an int for commit; a list of path strings for top_k_by_prefix.
Constraints
1 <= capacity <= 10^91 <= len(user_id), len(path), len(snapshot_id) <= 641 <= size <= capacity1 <= k <= 100- At most
10^4operations in total.
Examples
Example 1
Input: simulate_storage_service(100, ['stage_file', 'stage_file', 'stage_file', 'commit', 'top_k_by_prefix', 'backup', 'stage_file', 'commit', 'restore', 'top_k_by_prefix'], [['alice', '/docs/resume.pdf', 40], ['alice', '/docs/cover.pdf', 30], ['alice', '/media/photo.png', 50], ['alice'], ['alice', '/docs', 5], ['snap_1'], ['alice', '/docs/resume.pdf', 50], ['alice'], ['snap_1', 'keep_newer'], ['alice', '/docs', 1]])
Output: [True, True, False, 2, ['/docs/resume.pdf', '/docs/cover.pdf'], True, True, 1, True, ['/docs/resume.pdf']]
Hints
Hint 1
Keep three dictionaries: committed files per user, staged files per user, and snapshots keyed by id. Each maps path to size.
Hint 2
For every mutating call, build the would-be new state on the side, validate it, and only then replace the live state. Failed calls then leave no trace.
Hint 3
For stage_file, the capacity check is on the merge of committed and staged (staged overrides committed on the same path), not on the sum of both. For restore, check every user in the candidate state, and remember to copy data when taking a snapshot so it never aliases live state.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep all state in three dictionaries:
stored[user]maps path to size for committed files.pending[user]maps path to size for staged files.snaps[snapshot_id]holds a deep copy ofstoredtaken at backup time.
Every operation that could fail builds its candidate result separately, validates it, and only then replaces the live state. This makes "fail without changing anything" automatic.
Per operation
- stage_file: copy the user's staged map and set the new path and size. Then build the hypothetical post-commit state by copying the committed map and applying the staged map on top, since staged entries overwrite committed ones. If its total exceeds
capacity, returnFalseand keep the old staging area. Otherwise save the new staged map and returnTrue. - commit: if nothing is staged, return
0. Otherwise merge the staged map over the committed map, clear the staging area, and return the number of staged paths. No capacity check is done here because staging already validated it. - top_k_by_prefix: filter committed paths with
startswith, sort by(-size, path), and slice the firstk. Slicing handles the case where fewer thankpaths match. - backup: reject a duplicate id. Otherwise store a deep copy of
stored. - restore: reject an unknown snapshot or an invalid strategy. Build the candidate: for
"overwrite"it is a deep copy of the snapshot; for"keep_newer"it is a deep copy of the current state, with each snapshot file added if missing or replacing the current one only if strictly larger. If any user in the candidate exceedscapacity, returnFalse. Otherwise install the candidate. Staging is never touched.
Why it is correct
- Staging validates exactly the state that a commit would produce, so overwrites are accounted for as net size changes.
- Candidate-then-swap guarantees atomicity for
stage_fileandrestore. - Deep copies at backup and restore time keep snapshots immutable and independent of live data, so restoring the same snapshot repeatedly behaves the same way.
- The strict
>comparison inkeep_newergives the required tie rule (keep the current version). keep_newercan produce a union that exceeds capacity even though both inputs were valid, which is why the check runs over every user in the candidate.
Complexity
Let C be a user's committed file count, S their staged count, and N the total committed files across all users.
stage_fileandcommit: O(C + S) time and space.top_k_by_prefix: O(C · L + m log m) time for m matches and path length L.backup: O(N) time and extra space per snapshot.restore: O(N + snapshot size) time and space.
With at most 10^4 operations, this is comfortably fast.
Reference solution
from copy import deepcopy
from typing import List
def simulate_storage_service(capacity: int, operations: List[str], arguments: List[List]) -> List:
stored = {} # user -> {path: size}
pending = {} # user -> {path: size}
snaps = {} # snapshot id -> {user: {path: size}}
out = []
for op, args in zip(operations, arguments):
if op == "stage_file":
user, path, size = args
new_pending = dict(pending.get(user, {}))
new_pending[path] = size
after_commit = dict(stored.get(user, {}))
after_commit.update(new_pending)
if sum(after_commit.values()) > capacity:
out.append(False)
continue
pending[user] = new_pending
out.append(True)
elif op == "commit":
user = args[0]
staged_files = pending.get(user, {})
if staged_files:
merged = dict(stored.get(user, {}))
merged.update(staged_files)
stored[user] = merged
del pending[user]
out.append(len(staged_files))
else:
out.append(0)
elif op == "top_k_by_prefix":
user, prefix, k = args
files = stored.get(user, {})
matches = [(p, s) for p, s in files.items() if p.startswith(prefix)]
matches.sort(key=lambda item: (-item[1], item[0]))
out.append([p for p, _ in matches[:k]])
elif op == "backup":
sid = args[0]
if sid in snaps:
out.append(False)
else:
snaps[sid] = deepcopy(stored)
out.append(True)
elif op == "restore":
sid, strategy = args
if sid not in snaps or strategy not in ("overwrite", "keep_newer"):
out.append(False)
continue
snap = snaps[sid]
if strategy == "overwrite":
candidate = deepcopy(snap)
else:
candidate = deepcopy(stored)
for user, snap_files in snap.items():
cur = candidate.setdefault(user, {})
for p, s in snap_files.items():
if p not in cur or s > cur[p]:
cur[p] = s
if any(sum(files.values()) > capacity for files in candidate.values()):
out.append(False)
continue
stored = candidate
out.append(True)
return out