Simulate a Multi-User File Store with Quotas and Compression
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a command-driven in-memory file store with ownership, per-user quotas, prefix/suffix search, quota-driven eviction and size-changing renames.
You are given a log of commands to run against an initially empty in-memory file store. Process the commands in order and return one result per command.
commands[i] is the name of a command and params[i] is the list of its arguments. Every file name is a globally unique string, and every size is a non-negative integer. A failed command must leave the store completely unchanged.
Users and ownership
The store always contains a built-in user "admin" with unlimited capacity. Every other user has a fixed capacity and a current usage, which is the total size of the files they own. Usage may equal capacity but must never exceed it.
For "admin", the "remaining capacity" is reported as None, because it is unlimited.
Commands
add_file [name, size]
Create a file owned by "admin". Return True on success, or False if the name is already taken.
copy_file [name_from, name_to]
Create name_to with the same size and the same owner as name_from. The copy counts toward that owner's usage. Return True on success. Return False if the source does not exist, the destination already exists, or the owner's usage would exceed their capacity.
get_file_size [name]
Return the file's size, or None if it does not exist.
find_file [prefix, suffix]
Return a list of strings "name(size)" for every file whose name starts with prefix and ends with suffix. An empty prefix or suffix matches every name. Order the list by size descending, then by name ascending (plain string comparison). Return an empty list if nothing matches.
add_user [user_id, capacity]
Create a user with zero usage. Return True on success, or False if the user already exists (this includes "admin").
add_file_by [user_id, name, size]
Create a file owned by user_id. On success, return that user's remaining capacity (capacity - usage after the addition; None for "admin"). Return None if the user does not exist, the name is taken, or the addition would push usage above capacity.
update_capacity [user_id, capacity]
- If the user does not exist, return
None. - If the user is
"admin", change nothing and return0. - Otherwise set the new capacity. While the user's usage is still greater than the capacity, delete one of their files, choosing the one with the largest size and, among equal sizes, the lexicographically smallest name. Return the number of files deleted (
0if none were needed).
compress_file [user_id, name]
Valid only if the file exists and is owned by user_id, and name + ".COMPRESSED" is not already a file name. Replace the file with one named name + ".COMPRESSED", owned by the same user, with size floor(original_size / 2). Update the user's usage and return their remaining capacity (None for "admin"). Otherwise return None.
decompress_file [user_id, name]
Valid only if the file exists, is owned by user_id, and its name ends with ".COMPRESSED". The original name is name with that suffix removed, and it must not already exist. The new size is twice the stored size, and the user's usage after the replacement must not exceed their capacity. On success, replace the file, update the usage and return the remaining capacity (None for "admin"). Otherwise return None. Sizes are not remembered, so an odd original size does not round-trip (5 compresses to 2 and decompresses to 4).
If user_id in compress_file or decompress_file does not exist, the ownership check fails and the result is None.
Output
Return a list with one entry per command. Each entry is the value that command returns: a bool, an int, None, or a list of strings.
Constraints
len(commands) == len(params), and commands are limited to the ten listed above.- File names and user IDs are non-empty strings; sizes and capacities are non-negative integers.
- A file name is globally unique across all users.
- Failed commands must not modify any state.
- Capacity checks allow usage to equal capacity exactly.
Examples
Example 1
Input: run_storage_commands(['add_file', 'add_file', 'copy_file', 'get_file_size', 'find_file', 'copy_file'], [['logs/a.txt', 120], ['logs/b.txt', 80], ['logs/a.txt', 'archive/a.txt'], ['archive/a.txt'], ['logs/', '.txt'], ['missing.txt', 'new.txt']])
Output: [True, True, True, 120, ['logs/a.txt(120)', 'logs/b.txt(80)'], False]
Example 2
Input: run_storage_commands(['add_user', 'add_file_by', 'copy_file', 'compress_file', 'decompress_file', 'update_capacity', 'get_file_size'], [['alice', 100], ['alice', 'a.bin', 80], ['a.bin', 'copy.bin'], ['alice', 'a.bin'], ['alice', 'a.bin.COMPRESSED'], ['alice', 50], ['a.bin']])
Output: [True, 20, False, 60, 20, 1, None]
Hints
Hint 1
Keep two dictionaries: one from file name to (size, owner) and one from user ID to (capacity, usage). Treat admin as a user whose capacity is unlimited.
Hint 2
For every command, check all failure conditions first and only then change state. For anything that replaces a file, adjust the owner's usage by the exact size difference.
Hint 3
For find_file and update_capacity, sort with the key (-size, name). Eviction should stop as soon as usage is within capacity, removing only as many files as needed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a state-modelling problem more than an algorithmic one. Two dictionaries are enough:
filesmaps a file name to its size and owner.usersmaps a user ID to its capacity (Nonemeaning unlimited, used foradmin) and its current usage.
Each command is handled in a loop:
- Check every failure condition first (existence, duplicates, ownership, capacity).
- Only if all checks pass, mutate state through two small helpers:
putadds a file and increases the owner's usage, anddropremoves a file and decreases it.
Command details:
- Search scans all files, filters with
startswithandendswith, and sorts by(-size, name). - Copy reuses the source's owner and checks the owner's capacity for the extra size.
- Capacity update collects the user's files, sorts them by
(-size, name), and removes them one by one until usage is within the new capacity. It stops as soon as the condition holds. - Compress drops the old file and adds
name.COMPRESSEDwith half the size (integer division). The size shrinks, so no capacity check is needed. - Decompress checks that the net increase (
new_size - old_size) fits in the capacity, then swaps the files. The stored size is doubled, not restored, so odd sizes lose a unit.
Why it is correct
The invariant is that each user's usage equals the total size of the files they own. Every successful command changes files only through put and drop, which update exactly one user's usage by exactly the size change. Failed commands do nothing, so the invariant always holds. Capacity checks use usage + delta <= capacity, so reaching capacity exactly is allowed. Removing files in (-size, name) order and stopping as soon as usage fits gives the required eviction sequence, and the count of removals is the returned value.
Complexity
Let N be the number of files, m the number of search matches, and k the number of files one user owns.
add_file,add_file_by,copy_file,get_file_size,add_user: O(1) on average.compress_file,decompress_file: O(L) for a name of length L.find_file: O(N·L + m log m).update_capacity: O(N + k log k).
Space is O(N + U) for N files and U users.
Reference solution
from typing import List
def run_storage_commands(commands: List[str], params: List[List]) -> List:
SUFFIX = ".COMPRESSED"
files = {}
users = {"admin": {"capacity": None, "used": 0}}
out = []
def remaining(uid):
cap = users[uid]["capacity"]
return None if cap is None else cap - users[uid]["used"]
def fits(uid, extra):
cap = users[uid]["capacity"]
return cap is None or users[uid]["used"] + extra <= cap
def drop(name):
info = files.pop(name)
users[info["owner"]]["used"] -= info["size"]
def put(name, size, owner):
files[name] = {"size": size, "owner": owner}
users[owner]["used"] += size
for cmd, args in zip(commands, params):
if cmd == "add_file":
name, size = args
if name in files:
out.append(False)
else:
put(name, size, "admin")
out.append(True)
elif cmd == "copy_file":
src, dst = args
if src not in files or dst in files:
out.append(False)
continue
owner = files[src]["owner"]
size = files[src]["size"]
if not fits(owner, size):
out.append(False)
continue
put(dst, size, owner)
out.append(True)
elif cmd == "get_file_size":
name = args[0]
out.append(files[name]["size"] if name in files else None)
elif cmd == "find_file":
prefix, suffix = args
names = [n for n in files if n.startswith(prefix) and n.endswith(suffix)]
names.sort(key=lambda n: (-files[n]["size"], n))
out.append([f"{n}({files[n]['size']})" for n in names])
elif cmd == "add_user":
uid, cap = args
if uid in users:
out.append(False)
else:
users[uid] = {"capacity": cap, "used": 0}
out.append(True)
elif cmd == "add_file_by":
uid, name, size = args
if uid not in users or name in files or not fits(uid, size):
out.append(None)
continue
put(name, size, uid)
out.append(remaining(uid))
elif cmd == "update_capacity":
uid, cap = args
if uid not in users:
out.append(None)
continue
if uid == "admin":
out.append(0)
continue
users[uid]["capacity"] = cap
owned = [n for n, info in files.items() if info["owner"] == uid]
owned.sort(key=lambda n: (-files[n]["size"], n))
removed = 0
for n in owned:
if users[uid]["used"] <= cap:
break
drop(n)
removed += 1
out.append(removed)
elif cmd == "compress_file":
uid, name = args
if name not in files or files[name]["owner"] != uid:
out.append(None)
continue
new_name = name + SUFFIX
if new_name in files:
out.append(None)
continue
new_size = files[name]["size"] // 2
drop(name)
put(new_name, new_size, uid)
out.append(remaining(uid))
elif cmd == "decompress_file":
uid, name = args
if name not in files or files[name]["owner"] != uid or not name.endswith(SUFFIX):
out.append(None)
continue
orig = name[:-len(SUFFIX)]
if orig in files:
out.append(None)
continue
old_size = files[name]["size"]
new_size = 2 * old_size
if not fits(uid, new_size - old_size):
out.append(None)
continue
drop(name)
put(orig, new_size, uid)
out.append(remaining(uid))
return out