File Storage with Quotas, Copy, and Compression
Data Structure DesignModel answerLast updated
Build an in-memory file system tracking per-user storage limits, supporting file operations including duplication, compression, and quota-driven eviction.
Problem
Implement an in-memory file storage system that tracks user quotas and supports file manipulation operations.
Storage Model
Files have three properties:
name: unique identifier (string)size: storage consumed (positive integer)owner: which user owns it
Users have two properties:
capacity: maximum storage allowedused: current storage consumed
Constraint: For any user, used ≤ capacity must hold after every operation.
Operations to Implement
1. add_user(user_id, capacity) → bool
- Register a new user with the given capacity and
used = 0 - Return false if the user already exists
2. add_file_by(user_id, name, size) → bool
- Create a file owned by
user_id - Fail if: user doesn't exist, name is taken, or adding would violate the capacity constraint
3. add_file(name, size) → bool
- Create a file owned by a special
adminuser (has unlimited capacity) - The
adminuser should exist from initialization
4. copy_file(from_name, to_name) → bool
- Duplicate an existing file with a new name
- The copy inherits the original's size and owner
- Fail if: source doesn't exist, destination name exists, or owner's capacity would be exceeded
5. get_file_size(name) → int | null
- Return the file's size, or null if it doesn't exist
6. get_n_largest(prefix, suffix, n) → list[string]
- Find all files whose names start with
prefixAND end withsuffix - Return up to
nfiles formatted as"name(size)" - Sort by: size descending, then name ascending
7. update_capacity(user_id, new_capacity) → bool
- Change a user's capacity
- If
used > new_capacity, automatically delete the user's largest files (by size, breaking ties by smallest name) until the constraint is satisfied - Return false if user doesn't exist
8. compress_file(name) → bool
- Transform a file into compressed form
- Only works if the file exists and is not already compressed
- Compressed file: append
".compressed"to the name, set size tofloor(original_size / 2) - Replace the original (remove old, add new)
- Owner remains the same
9. decompress_file(name) → bool
- Reverse compression
- Only works if name ends with
".compressed" - Remove the suffix from the name, multiply size by 2
- Fail if: the decompressed name already exists, or owner would exceed capacity
- Replace the compressed file with the decompressed one
Implementation Notes
- Choose clear conventions for edge cases (e.g., what happens with size-1 files, empty base names)
- Focus on correct quota tracking across all operations
- Aim for efficiency in finding and removing largest files (up to ~100,000 operations expected)
Hints
Hint 1
Track file metadata and user quotas in hash maps for O(1) lookups
Hint 2
Use a heap per user to efficiently find their largest files for eviction
Hint 3
Handle stale heap entries with lazy deletion using unique identifiers
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to maintain consistent state across multiple interdependent operations. The core challenge is correct quota bookkeeping combined with efficient file eviction.
Key Design Decisions
Data Structures:
-
Files map:
name → (size, owner, unique_id)- Central source of truth for all file metadata
unique_iddistinguishes different file instances with the same name
-
Users map:
user_id → [capacity, used]- Tracks quotas and current usage
-
Heaps map:
user_id → min_heap of (-size, name, unique_id)- One heap per user to quickly find their largest files
- Negative size for max-heap behavior
- Name as tiebreaker for deterministic ordering
Lazy Deletion Strategy:
When a file is removed, its heap entry stays in place. During eviction, we verify each popped entry still references a live file by comparing unique_id. This avoids the cost of searching and removing specific heap entries (O(n) operation).
Conventions:
- Compression suffix:
".compressed" - Eviction priority: largest size first; among equal sizes, lexicographically smallest name first
- Admin user created at initialization with infinite capacity
- Add operations fail if the name already exists (preventing overwrites)
Core Implementation Pattern
All mutations flow through two helpers:
def _insert(name, size, owner):
# Assign fresh unique_id
# Add to files map
# Increment owner's used
# Push to owner's heap
def _remove(name):
# Pop from files map
# Decrement owner's used
# Return size and owner (heap entry stays)
This centralization guarantees used changes happen in exactly one place, preventing accounting bugs.
Operation Breakdown
Simple Operations (O(1) to O(log n)):
add_user: Direct map insertionadd_file_by/add_file: Check capacity, then_insertcopy_file: Check capacity for owner, then_insertnew nameget_file_size: Map lookup
Compression Operations:
compress_file: Check name doesn't end with suffix,_removeold,_insertnew withsize // 2decompress_file: Check name ends with suffix and base name is free, verify capacity,_removeold,_insertnew withsize * 2
Eviction (update_capacity):
while user_used > new_capacity:
pop from user's heap
if entry's unique_id matches files map:
remove that file
else:
discard stale entry
The unique_id check is critical. Consider: file "A" is deleted, then a new file "A" is created. The old heap entry shouldn't trigger removal of the new file.
Filtering (get_n_largest):
- Scan all files, filter by prefix/suffix
- Sort by
(-size, name) - Take first n, format output
Correctness Invariants
-
Quota accuracy:
usedequals the sum of sizes of files owned by that user- Only
_insertand_removemodifyused - Each modifies by exactly the size added/removed
- Only
-
Capacity enforcement: All mutations check capacity before committing
- Add/copy/decompress: verify
used + new_size ≤ capacity - Compress: new size ≤ old size, so always safe
- Add/copy/decompress: verify
-
Heap validity: Every live file appears once in its owner's heap with the current
unique_id- Pushed at creation time
- Stale entries filtered during eviction
Complexity Analysis
Operations (M total, F live files):
- Add/copy/compress/decompress: O(log M) per operation (heap push)
update_capacity: O(k log M) where k = files evicted + stale entries encountered- Amortized efficient: each entry pushed once, popped at most once across all calls
get_n_largest: O(F log F) for full scan and sort- Can optimize to O(F + n log n) with heap-based selection
Space: O(M) worst case (heap holds all historical entries until evicted)
Edge Cases
- Size-1 compression: Results in size 0 (allowed)
- Decompressing ".compressed": Base name is empty (should fail or handle explicitly)
- Copy from admin: Always succeeds (infinite capacity)
- Compress already compressed: Detect suffix, fail
- Decompress to existing name: Pre-check, fail
- Update capacity on missing user: Return false immediately
- Lossy compression: Compressing size 5 → 2, decompressing → 4 (not 5)
Sample Code Structure
class FileStorage:
def __init__(self):
self.files = {} # name -> (size, owner, uid)
self.users = {"admin": [float('inf'), 0]}
self.heaps = defaultdict(list)
self.next_uid = 0
def _insert(self, name, size, owner):
uid = self.next_uid
self.next_uid += 1
self.files[name] = (size, owner, uid)
self.users[owner][1] += size
heappush(self.heaps[owner], (-size, name, uid))
def _remove(self, name):
size, owner, _ = self.files.pop(name)
self.users[owner][1] -= size
return size, owner
def compress_file(self, name):
if name not in self.files or name.endswith(".compressed"):
return False
size, owner, _ = self.files[name]
self._remove(name)
self._insert(name + ".compressed", size // 2, owner)
return True
def update_capacity(self, user_id, new_cap):
if user_id not in self.users:
return False
self.users[user_id][0] = new_cap
heap = self.heaps[user_id]
while self.users[user_id][1] > new_cap:
_, fname, uid = heappop(heap)
if fname in self.files and self.files[fname][2] == uid:
self._remove(fname)
return True
Time Complexity: O(log M) for most operations, O(k log M) for eviction, O(F log F) for filtering
Space Complexity: O(M)
Common Mistakes
- Forgetting to check capacity before mutations: Leads to violated invariants
- Not using unique IDs: Lazy deletion fails when names are reused
- Updating used incorrectly in compound operations: Double-counting or missing updates
- Inefficient eviction: Re-sorting all files on each capacity update
- Off-by-one in compression: Using
size / 2(float) instead ofsize // 2(integer) - Allowing compression of already-compressed files: Creates confusing double-suffix names