Build a Multi-User File System with Quotas and Compression
Data Structure DesignAuto-graded · 16 test casesLast updated
Design an in-memory file manager tracking per-user storage limits, file operations, pattern matching, and size adjustments with atomic quota enforcement.
You are building an in-memory file management system that tracks files, enforces per-user storage limits, and supports file resizing operations. Implement a function that processes a sequence of operations on this system.
Your function receives two parallel lists: operations (operation names) and arguments (corresponding parameters for each operation). Process them in order and return a list of results.
Operations
set_user_quota — [user_id: str, quota: int]
Establishes a maximum storage limit of quota bytes for user_id. Returns False if the user currently occupies more than quota bytes (reject the change); otherwise applies the limit and returns True. Users without an explicit quota have unlimited storage.
add_file — [user_id: str, path: str, size: int]
Creates a file owned by user_id at path consuming size bytes. Returns False if path already exists or if adding this file would push user_id over their quota; returns True on success.
copy_file — [source_path: str, dest_path: str]
Duplicates the file at source_path to dest_path. The copy has the same owner and size as the original. Returns False if source_path does not exist, dest_path already exists, or the operation would exceed the owner's quota; returns True on success.
search_files — [prefix: str, suffix: str]
Returns a sorted list (lexicographically ascending) of all file paths that begin with prefix and end with suffix.
compress_file — [path: str, factor: float]
Adjusts the file at path to a new size equal to floor(current_size × factor) bytes. The owner's storage usage updates accordingly. If factor > 1.0 (expansion) and the increase would exceed the owner's quota, the operation must fail atomically: return False and leave both file size and usage unchanged. Returns False if path does not exist; returns True on successful resize.
Constraints
1 ≤ len(user_id), len(path) ≤ 1001 ≤ size, quota ≤ 10^90.0 < factor ≤ 10.0- At most
5 × 10^4total operations
Examples
Example 1
Input: process_file_operations(['set_user_quota', 'add_file', 'add_file', 'copy_file', 'compress_file', 'copy_file', 'search_files', 'compress_file'], [['u1', 100], ['u1', '/docs/notes.txt', 60], ['u1', '/docs/code.py', 50], ['/docs/notes.txt', '/backup/notes.txt'], ['/docs/notes.txt', 0.5], ['/docs/notes.txt', '/backup/notes.txt'], ['/', '.txt'], ['/docs/notes.txt', 3]])
Output: [True, True, False, False, True, True, ['/backup/notes.txt', '/docs/notes.txt'], False]
Hints
Hint 1
Track two mappings: one from paths to (owner, size) pairs, and one from user IDs to current usage and quota.
Hint 2
Before any mutation that increases a user's storage, validate that the new total stays within their quota. Only commit the change after validation passes.
Hint 3
For compress_file, compute the size delta first. If it's positive (expansion), check the quota; if negative or zero (compression), the operation always succeeds from a quota perspective.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining consistency between individual file sizes and aggregate per-user storage totals while enforcing quota limits. The solution keeps two independent hash tables: one mapping file paths to their owner and size, and another tracking each user's current storage consumption and quota.
Every operation that increases storage (adding files, copying files, or expanding compressed files) follows the same pattern: compute the intended change, validate it against the relevant user's quota, and only then commit the mutation. This "validate-then-commit" discipline makes quota enforcement atomic—if validation fails, no state is modified.
Operation Details:
set_user_quota: Check if the user's current usage exceeds the proposed limit. If so, reject; otherwise, store the new quota.add_file: Verify the path is unused and that addingsizebytes keeps the user within their limit. Users without an explicit quota have unlimited capacity.copy_file: Look up the source's owner and size, then treat the copy as adding a file of that size for that owner.search_files: Scan all paths, filter by prefix and suffix conditions independently, then sort the results.compress_file: Calculate the new size asfloor(size × factor)and determine the storage delta. If the delta is positive (expansion), check the quota; negative or zero deltas (compression) always pass. Update both the file size and user usage atomically.
The critical insight for compress_file is that computing the delta first allows a single validation step regardless of whether the operation shrinks or grows the file.
Why It Works:
Each mutating operation changes exactly one file and updates exactly one user's usage by the same amount, preserving the invariant that a user's tracked usage equals the sum of their file sizes. Quota checks happen before any write, so failed operations leave state unchanged.
Complexity:
set_user_quota,add_file,copy_file,compress_file: O(1) average per operation (hash table lookups and updates)search_files: O(N·L + K log K·L) where N is the number of files, L is maximum path length, and K is the number of matches (linear scan plus sorting)- Space: O(N·L + U) for N files and U users
With up to 50,000 operations, the linear search for pattern matching is acceptable.
Edge Cases:
- Users with no quota set have unlimited storage
- Usage exactly equal to quota is allowed
- Setting a quota below current usage is rejected; equal to or above current usage is accepted
- Compression can reduce a file to 0 bytes; it still exists and appears in searches
- Expansion attempts for users without quotas always succeed
factor = 1.0is a valid no-op that returnsTrue- Empty prefix or suffix matches all paths on that end
import math
from typing import List
def process_file_operations(operations: List[str], arguments: List[List]) -> List:
file_registry = {} # path -> (owner, size)
user_quotas = {} # user_id -> quota (or None for unlimited)
user_usage = {} # user_id -> current bytes used
results = []
for op, args in zip(operations, arguments):
if op == "set_user_quota":
user_id, quota = args
current = user_usage.get(user_id, 0)
if current > quota:
results.append(False)
else:
user_quotas[user_id] = quota
results.append(True)
elif op == "add_file":
user_id, path, size = args
if path in file_registry:
results.append(False)
else:
current = user_usage.get(user_id, 0)
limit = user_quotas.get(user_id, float('inf'))
if current + size > limit:
results.append(False)
else:
file_registry[path] = (user_id, size)
user_usage[user_id] = current + size
results.append(True)
elif op == "copy_file":
source_path, dest_path = args
if source_path not in file_registry or dest_path in file_registry:
results.append(False)
else:
owner, size = file_registry[source_path]
current = user_usage.get(owner, 0)
limit = user_quotas.get(owner, float('inf'))
if current + size > limit:
results.append(False)
else:
file_registry[dest_path] = (owner, size)
user_usage[owner] = current + size
results.append(True)
elif op == "search_files":
prefix, suffix = args
matches = [
path for path in file_registry
if path.startswith(prefix) and path.endswith(suffix)
]
results.append(sorted(matches))
elif op == "compress_file":
path, factor = args
if path not in file_registry:
results.append(False)
else:
owner, old_size = file_registry[path]
new_size = math.floor(old_size * factor)
delta = new_size - old_size
current = user_usage.get(owner, 0)
limit = user_quotas.get(owner, float('inf'))
new_usage = current + delta
if new_usage > limit:
results.append(False)
else:
file_registry[path] = (owner, new_size)
user_usage[owner] = new_usage
results.append(True)
return results