Hierarchical Storage Simulator with Auto-Renamed Duplicates
Data Structure DesignAuto-graded · 20 test casesLast updated
Simulate an in-memory directory tree with auto-created folders, numbered duplicate file names that respect extensions, content lookup, and sorted listings.
You are building a small in-memory storage tree that starts with only the root directory /. It supports four commands, and you must replay a sequence of them and report what each one returns.
Commands
Every path is absolute (it begins with /).
-
mkdirwith one argumentpath: make every directory alongpaththat does not exist yet, including intermediate ones. If everything already exists, nothing changes. Result:None. -
create_filewith argumentspathandcontent:- The last component of
pathis the requested file name, and the preceding components form the parent directory. Create any missing parent directories. - If the requested name is not used by any entry (file or subdirectory) in the parent directory, store the file under that name.
- Otherwise, the file gets a numbered name. Try
k = 1, 2, 3, ...in order and use the firstkfor which the numbered name is not used by any entry in that parent directory. - Build the numbered name from the requested name as follows. Let
dbe the index of the last.in it.- If
d > 0(there is a dot that is not the first character), put(k)right before that last dot. For example,doc.txtbecomesdoc(1).txt, anda.b.cbecomesa.b(1).c. A trailing dot works the same way:a.becomesa(1).. - If there is no dot, or the only dot is the first character, append
(k)to the end. For example,databecomesdata(1)and.envbecomes.env(1).
- If
Numbering is applied to the requested name as given, so asking for a name that already looks numbered, such as
notes(1).txt, is handled by the same rule (notes(1)(1).txt).Result: the final file name that was stored (just the name, not the full path).
- The last component of
-
read_filewith one argumentpath: Result: the content of the file stored at exactly that path. The file is guaranteed to exist. -
lswith one argumentpath:- If
pathis a directory, Result: the names of its direct children (files and subdirectories), sorted in plain lexicographic (code point) order. - If
pathis a file, Result: a list containing only that file's name.
- If
Names are case-sensitive.
Your task
Implement a function that receives a list of command names and a parallel list of argument lists. Process the commands in order, starting from an empty tree, and return a list with one result per command, using the results defined above (None for mkdir).
Constraints
commandsandparamshave the same length, at most10^4.commands[i]is one of"mkdir","create_file","read_file","ls", andparams[i]holds the arguments for that command in the order described above.- All paths are absolute and start with
/. None ends with/except the root path/itself. - Path components contain only letters, digits,
.and_. - Paths are well formed, and
read_fileandlsare only used on paths that exist.
Examples
Example 1
Input: simulate_storage_ops(['mkdir', 'ls', 'create_file', 'create_file', 'create_file', 'ls', 'read_file'], [['/a/b'], ['/a'], ['/a/b/notes.txt', 'first'], ['/a/b/notes.txt', 'second'], ['/a/b/notes.txt', 'third'], ['/a/b'], ['/a/b/notes(1).txt']])
Output: [None, ['b'], 'notes.txt', 'notes(1).txt', 'notes(2).txt', ['notes(1).txt', 'notes(2).txt', 'notes.txt'], 'second']
Example 2
Input: simulate_storage_ops(['create_file', 'create_file', 'create_file', 'create_file', 'ls'], [['/data', 'val1'], ['/data', 'val2'], ['/.env', 'secret'], ['/.env', 'secret2'], ['/']])
Output: ['data', 'data(1)', '.env', '.env(1)', ['.env', '.env(1)', 'data', 'data(1)']]
Hints
Hint 1
Keep two hash maps keyed by full absolute path: one from each directory to the set of its child names, and one from each file path to its content.
Hint 2
To split a requested file name for numbering, look at the last dot: only when its index is greater than 0 does it count as an extension separator. Dotfiles like `.env` and names without dots just get `(k)` appended.
Hint 3
For a collision, start `k` at 1 on every call and keep incrementing until the candidate name is absent from the parent's child set. This guarantees the smallest `k`. Don't forget that a subdirectory name also blocks a file name.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Instead of building an explicit tree of node objects, keep two hash maps keyed by absolute path:
dirs: directory path -> set of names of its direct children (files and subdirectories). It starts as{"/": set()}.files: file path -> content.
Each command then reduces to a few lookups:
mkdir: walk the path components, building each prefix (/a,/a/b, ...). For each one, add the component name to its parent's child set and make sure the prefix exists as a key indirs. Usingsetdefaultand sets makes repeated calls harmless.create_file: split the path into the parent and the requested name, andmkdirthe parent. If the name is free, use it. If not, split the requested name at its last dot (only when the dot index is greater than 0) into a stem and an extension. Then trystem(1)ext,stem(2)ext, ... until a candidate is not in the parent's child set and not a stored file. Record the name in the parent's set and store the content under the full path.read_file: a direct dictionary lookup.ls: if the path is a stored file, return its basename in a list. Otherwise returnsorted(dirs[path]).
Why it is correct
- Every directory is registered in its parent's child set at creation, so
dirs[p]is exactly the set of direct children ofp. - Probing always starts at
k = 1and increases by one, so the first free candidate has the smallest validk. - Checking the parent's child set also catches clashes with subdirectories, so a file and a directory never share a name in one parent.
- The rule
dot > 0handles dotfiles (.env->.env(1)), multiple dots (a.b.c->a.b(1).c), and names without dots. - Python's default string sort is the required lexicographic order. For instance
(sorts before., giving["notes(1).txt", "notes(2).txt", "notes.txt"].
Complexity
Let L be the maximum path length, c the number of children of the listed directory, and p the number of probes in a collision.
mkdir: O(L) prefix-building steps, each hashing a string of length up to L, so about O(L^2) worst case (small in practice).create_file: the cost ofmkdirplus O(p * L) for the probes.read_file: O(L).ls: O(c log c) comparisons for sorting.
Space is proportional to the total size of all paths and file contents. With at most 10^4 commands this is very fast.
Reference solution
from typing import List, Optional
class _Storage:
def __init__(self):
self.dirs = {"/": set()}
self.files = {}
def _parts(self, path):
return [p for p in path.split("/") if p]
def mkdir(self, path):
current = ""
for part in self._parts(path):
parent = current or "/"
current = (current + "/" + part) if current else "/" + part
self.dirs.setdefault(parent, set()).add(part)
self.dirs.setdefault(current, set())
def create_file(self, path, content):
parts = self._parts(path)
parent_parts, requested = parts[:-1], parts[-1]
parent = "/" + "/".join(parent_parts) if parent_parts else "/"
self.mkdir(parent)
base = parent.rstrip("/")
name = requested
if name in self.dirs[parent] or base + "/" + name in self.files:
dot = requested.rfind(".")
if dot > 0:
stem, ext = requested[:dot], requested[dot:]
else:
stem, ext = requested, ""
k = 1
while True:
candidate = f"{stem}({k}){ext}"
if candidate not in self.dirs[parent] and base + "/" + candidate not in self.files:
name = candidate
break
k += 1
self.dirs[parent].add(name)
self.files[base + "/" + name] = content
return name
def read_file(self, path):
return self.files[path]
def ls(self, path):
if path in self.files:
return [path.rsplit("/", 1)[-1]]
return sorted(self.dirs[path])
def simulate_storage_ops(commands: List[str], params: List[List[str]]) -> List[Optional[str]]:
store = _Storage()
results = []
for cmd, args in zip(commands, params):
if cmd == "mkdir":
store.mkdir(args[0])
results.append(None)
elif cmd == "create_file":
results.append(store.create_file(args[0], args[1]))
elif cmd == "read_file":
results.append(store.read_file(args[0]))
elif cmd == "ls":
results.append(store.ls(args[0]))
else:
raise ValueError("Unknown command")
return results