Path-Keyed File Store with Per-User Storage Quotas
Data Structure DesignAuto-graded · 20 test casesLast updated
Simulate a command stream on an in-memory file store with admin and user-owned files, prefix/suffix search, copying, and quota-driven eviction.
You are building a small in-memory file store and must replay a sequence of commands against it.
Files are identified by a full path string such as "/docs/a.txt". Paths are plain strings: there are no directories to track, and every path is unique across the whole store. Each file has an integer size and an owner. The owner is either the built-in admin or a registered user. The admin has no storage limit and is not a registered user.
Implement run_storage_commands(commands, params). The i-th command is commands[i] and its arguments are params[i]. Process the commands in order, starting from an empty store with no users, and return a list with one result per command.
Commands
| Command | Arguments | Behavior | Result |
|---|---|---|---|
addFile | [name, size] | Create an admin-owned file. Fails if name already exists. | True if created, else False |
copyFile | [source, destination] | Create destination with the same size and the same owner as source. Succeeds only if source exists and destination does not. | True on success, else False |
getFileSize | [name] | Look up a file's size. | The size, or -1 if there is no such file |
findFiles | [prefix, suffix] | Find every file whose name starts with prefix and ends with suffix. An empty prefix or suffix matches every name. | A list of strings "<name>(<size>)", ordered by size descending, then by name ascending (plain string comparison) |
addUser | [user_id, capacity] | Register a user with the given storage capacity. Fails if the user is already registered. | True if registered, else False |
addFileByUser | [user_id, name, size] | Create a file owned by user_id. It succeeds only if the user is registered, name is not already taken (by anyone), and used + size <= capacity, where used is the total size of the files that user currently owns. | The user's remaining capacity (capacity - used) after the add, or -1 on failure |
updateUserCapacity | [user_id, new_capacity] | Set the user's capacity to new_capacity. Then, while the user's used storage is greater than new_capacity, delete one of that user's files: the one with the largest size, and among equal sizes the one with the lexicographically largest name. Deleted names become free again. | The number of files deleted, or -1 if the user is not registered |
Rules to note
- A copy of a user-owned file counts toward that user's used storage.
copyFiledoes not check capacity: it always succeeds when the source exists and the destination is free, even if the owner ends up above capacity. - Copying a file onto its own name fails, because the destination already exists.
- A file that brings usage exactly up to capacity is allowed.
- Raising a capacity, or lowering it to a value that is still at least the current usage, deletes nothing and returns
0, but the new capacity is still stored. - Zero-size files are valid.
- Admin-owned files never count against any user's capacity.
- Files deleted by
updateUserCapacitystop appearing ingetFileSizeandfindFiles.
Constraints
len(commands) == len(params), and every command name is one of the seven listed above.- Paths and user IDs are non-empty strings, except that
prefixandsuffixinfindFilesmay be empty. - File sizes and capacities are non-negative integers.
- Argument lists always have the arity shown in the table.
- The expected result for each command is exactly as specified, so results must be returned as Python
bool,int, orlist[str]values as appropriate.
Examples
Example 1
Input: run_storage_commands(['addFile', 'addFile', 'getFileSize', 'copyFile', 'findFiles'], [['/docs/a.txt', 120], ['/docs/a.txt', 50], ['/docs/a.txt'], ['/docs/a.txt', '/backup/a.txt'], ['/', 'txt']])
Output: [True, False, 120, True, ['/backup/a.txt(120)', '/docs/a.txt(120)']]
Example 2
Input: run_storage_commands(['addUser', 'addFileByUser', 'addFileByUser', 'getFileSize', 'updateUserCapacity', 'findFiles'], [['u1', 100], ['u1', '/a', 40], ['u1', '/b', 60], ['/b'], ['u1', 50], ['/', '']])
Output: [True, 60, 0, 60, 1, ['/a(40)']]
Hints
Hint 1
Keep one dictionary from path to (size, owner) as the single source of truth for files, and one dictionary from user ID to its capacity and running used total.
Hint 2
Only user-owned files change a user's used total: update it on add and copy, and also when files are evicted. Do not apply any capacity check on copies.
Hint 3
For eviction, collect the user's files, sort them by size descending with ties broken by name descending, and delete from the front until used <= new capacity. Sorting by (size, name) with reverse=True does this in one step.
Hint 4
For findFiles, a linear scan with startswith and endswith followed by sorting on the key (-size, name) is enough.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a state-simulation problem. The main work is choosing a data model and keeping it consistent across all seven commands.
Keep two dictionaries:
files: path ->(size, owner), whereownerisNonefor admin files and a user ID otherwise. It is the only record of which files exist, so one global namespace enforces unique names across admin and user files.users: user ID ->[capacity, used], whereusedis a running total of the sizes of that user's files.
Each command then follows directly:
- addFile: reject if the path exists, otherwise insert with owner
None. - copyFile: require the source to exist and the destination to be free. Insert the same
(size, owner)under the new path. If the owner is a user, add the size to theirused. No capacity check is performed, as the statement requires. - getFileSize: dictionary lookup, or
-1. - findFiles: scan all paths, keep those passing
startswithandendswith, sort by(-size, name), and format asname(size). - addUser: reject duplicates, otherwise store
[capacity, 0]. - addFileByUser: fail with
-1if the user is unknown, the name is taken, orused + size > capacity. Otherwise insert the file, increaseused, and returncapacity - used. - updateUserCapacity: store the new capacity, gather the user's files, and sort them by
(size, name)in reverse order. That gives the largest size first and, on ties, the lexicographically largest name first. Delete files in that order untilused <= new_capacity, and return the number deleted.
Why it is correct
- Every mutation (add, copy, delete) changes
filesand the owner'susedtogether, sousedalways equals the total size of the files that user owns. - Because the eviction loop checks
used <= new_capacitybefore each deletion, it stops as soon as the limit is met and never deletes extra files. - The sort keys match the required orderings exactly:
(-size, name)for search, and(size, name)descending for eviction. - Admin files have owner
None, so they never affect any user's usage.
Complexity
Let N be the number of files, K the number of search matches, F the number of files for the user being updated, and L the typical path length.
addFile,copyFile,getFileSize,addUser,addFileByUser: O(L) each, because hashing the string dominates.findFiles: O(N·L + K log K).updateUserCapacity: O(N + F log F) with the scan used here.- Space: O(N·L + U) for the file and user maps, where U is the number of users.
Reference solution
from typing import List
def run_storage_commands(commands: List[str], params: List[List]) -> List:
files = {} # path -> (size, owner); owner None means admin
users = {} # user_id -> [capacity, used]
out = []
for cmd, args in zip(commands, params):
if cmd == "addFile":
name, size = args
if name in files:
out.append(False)
else:
files[name] = (size, None)
out.append(True)
elif cmd == "copyFile":
source, destination = args
if source not in files or destination in files:
out.append(False)
else:
size, owner = files[source]
files[destination] = (size, owner)
if owner is not None:
users[owner][1] += size
out.append(True)
elif cmd == "getFileSize":
name = args[0]
out.append(files[name][0] if name in files else -1)
elif cmd == "findFiles":
prefix, suffix = args
matches = [(name, size) for name, (size, _) in files.items()
if name.startswith(prefix) and name.endswith(suffix)]
matches.sort(key=lambda item: (-item[1], item[0]))
out.append([f"{name}({size})" for name, size in matches])
elif cmd == "addUser":
user_id, capacity = args
if user_id in users:
out.append(False)
else:
users[user_id] = [capacity, 0]
out.append(True)
elif cmd == "addFileByUser":
user_id, name, size = args
if (user_id not in users or name in files
or users[user_id][1] + size > users[user_id][0]):
out.append(-1)
else:
files[name] = (size, user_id)
users[user_id][1] += size
out.append(users[user_id][0] - users[user_id][1])
elif cmd == "updateUserCapacity":
user_id, new_capacity = args
if user_id not in users:
out.append(-1)
continue
users[user_id][0] = new_capacity
owned = [(size, name) for name, (size, owner) in files.items()
if owner == user_id]
owned.sort(reverse=True) # size desc, then name desc
removed = 0
for size, name in owned:
if users[user_id][1] <= new_capacity:
break
del files[name]
users[user_id][1] -= size
removed += 1
out.append(removed)
else:
raise ValueError(f"Unknown command: {cmd}")
return out