Design a Deduplicated Storage System
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate file system operations while maintaining deduplicated content storage using reference counting.
Design an in-memory storage manager that automatically deduplicates file contents across different file paths. When multiple files have identical content payloads, the payload should be stored efficiently so that duplicate contents consume minimal memory overhead.
You will process a sequence of file operations provided as two parallel lists: operations (the method names) and arguments (the parameter lists for each method call).
The supported operations are:
-
write_file(path, content):- Saves
contentatpath. - If
pathalready exists, overwrites its content with the new payload. - Return value:
None(represented asnullin output lists).
- Saves
-
read_file(path):- Returns the content stored at
path. - If
pathdoes not exist, returnsNone.
- Returns the content stored at
-
delete_file(path):- Removes the file at
path. - Returns
Trueif the file was present and deleted, orFalseifpathdid not exist.
- Removes the file at
-
count_unique_contents():- Returns the number of distinct, non-orphaned content strings currently referenced by at least one existing path.
If an operation (such as an overwrite or deletion) causes a content payload to lose its last referencing file path, that content payload must no longer be tracked or counted.
Write a function run_file_system_operations(operations: List[str], arguments: List[List[str]]) -> List[object] that processes the sequence of calls in order and returns a list containing the result of each operation.
Constraints
1 <= len(operations) == len(arguments) <= 20,000operations[i]is one of"write_file","read_file","delete_file", or"count_unique_contents".- Arguments match the expected signature of each command:
write_file: two string arguments[path, content].read_file: one string argument[path].delete_file: one string argument[path].count_unique_contents: empty list[].
- All string comparisons (paths and contents) are case-sensitive.
contentmay be any string, including the empty string"".
Examples
Example 1
Input: run_file_system_operations(['write_file', 'write_file', 'count_unique_contents', 'read_file', 'write_file', 'count_unique_contents', 'delete_file', 'count_unique_contents', 'read_file'], [['/a/b/c.txt', 'market_data_v1'], ['/a/b/e.txt', 'market_data_v1'], [], ['/a/b/c.txt'], ['/a/b/c.txt', 'market_data_v2'], [], ['/a/b/e.txt'], [], ['/nonexistent']])
Output: [None, None, 1, 'market_data_v1', None, 2, True, 1, None]
Hints
Hint 1
Use two hash maps: one mapping each file path to its content payload, and another mapping each content payload to its active reference count.
Hint 2
When overwriting an existing file path, remember to decrement the reference count of the old content before updating the path's pointer.
Hint 3
When a content string's reference count drops to zero, remove it from the reference counting map so that count_unique_contents remains accurate.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To maintain deduplicated file storage and keep track of unique active content payloads, we separate path management from content tracking:
- Path-to-Content Map (
file_map): Maps each stringpathto its current stringcontent. - Reference Counting Map (
content_ref_counts): Maps each activecontentpayload to the integer count of file paths currently pointing to it.
For each operation in the input list:
-
write_file(path, content):- If
pathis already present, look up its previous content payload, decrement its reference count incontent_ref_counts, and remove the key if the count reaches zero. - Set
file_map[path] = contentand incrementcontent_ref_counts[content]. - Append
Noneto output.
- If
-
read_file(path):- Look up
pathinfile_map. Returnfile_map[path]if present, orNoneif missing.
- Look up
-
delete_file(path):- If
pathdoes not exist infile_map, appendFalse. - Otherwise, remove
pathfromfile_map, decrement the reference count of its content incontent_ref_counts(deleting the key if count drops to 0), and appendTrue.
- If
-
count_unique_contents():- Return the number of keys currently in
content_ref_counts.
- Return the number of keys currently in
Complexity
-
Time Complexity:
write_file,read_file, anddelete_file: $O(L)$ where $L$ is the string length (for hashing and lookup).count_unique_contents: $O(1)$ time sincelen(dict)is a constant-time check.- Overall time for $N$ operations is $O(N \cdot L)$.
-
Space Complexity:
- $O(U \cdot L_{\text{content}} + P \cdot L_{\text{path}})$ where $U$ is the number of distinct contents and $P$ is the number of active file paths.
Python Reference Solution
from typing import List
def run_file_system_operations(operations: List[str], arguments: List[List[str]]) -> List[object]:
file_map = {}
content_ref_counts = {}
results = []
for op, args in zip(operations, arguments):
if op == "write_file":
path, content = args
# If path already exists, decrement the refcount of previous content
if path in file_map:
old_content = file_map[path]
content_ref_counts[old_content] -= 1
if content_ref_counts[old_content] == 0:
del content_ref_counts[old_content]
file_map[path] = content
content_ref_counts[content] = content_ref_counts.get(content, 0) + 1
results.append(None)
elif op == "read_file":
path = args[0]
results.append(file_map.get(path))
elif op == "delete_file":
path = args[0]
if path not in file_map:
results.append(False)
else:
old_content = file_map.pop(path)
content_ref_counts[old_content] -= 1
if content_ref_counts[old_content] == 0:
del content_ref_counts[old_content]
results.append(True)
elif op == "count_unique_contents":
results.append(len(content_ref_counts))
return results