Build a Path-Addressed Tree Store and a Bounded Ring Buffer
Data Structure DesignModel answerLast updated
Design an in-memory hierarchical path store with strict parent-existence errors, plus a fixed-capacity FIFO queue where every operation is constant time.
This is a two-part design-and-implement exercise. Talk through your data structures before you write code, then implement, then reason about cost.
Part A — Hierarchical in-memory path store
Support a small filesystem-like tree with these calls: ls(path), mkdir(path), createFile(path, content), appendToFile(path, content), readFile(path).
Rules:
- Paths are absolute and slash-separated ("UNIX style"). The root is
/. No path other than/may end with a slash. - Strict parent rule: if any ancestor directory in the path is missing, the call fails and nothing is created. So
mkdir("/a/b")fails when/adoes not exist, andcreateFile("/a/b/c.txt", ...)fails when/a/bdoes not exist. lson a directory returns its immediate children's names sorted ascending;lson a file returns a one-element list with that file's name.- No permission model, no concurrency. Reject malformed input: empty segments (from doubled slashes or trailing slashes), and anything unreasonable you want to define.
- It must stay efficient when the tree holds a very large number of paths.
Deliver: the data structures and API contract, the implementation, per-operation and total time/space complexity, and a discussion of root-directory and invalid-path edge cases.
Part B — Bounded FIFO queue
Implement a queue with a constructor taking capacity and these methods: enQueue(x) -> bool, deQueue() -> bool, Front() -> optional value, Rear() -> optional value, isEmpty() -> bool, isFull() -> bool. Every operation must be O(1) time with O(capacity) space.
Deliver: the implementation, why you chose that structure over alternatives (linked nodes vs. ring buffer), a correctness argument, and the final complexity.
Hints
Hint 1
Model each directory as a hash map from child name to child node, so a lookup never scans siblings. Resolving a path is then one map probe per segment, and the parent rule falls out naturally if the resolver never inserts anything.
Hint 2
Split the work in two helpers: one that validates and splits the path into segments, and one that walks an existing chain of segments from the root and raises if a link is missing. Only the create operations may add a node, and only after every check passes, so failures never leave half-built state.
Hint 3
For the queue, a fixed array plus a head index and a size counter beats a linked list: no per-element allocation, no pointer chasing, and full/empty is decided by the size counter instead of by comparing indices.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A — Hierarchical path store
Core idea. The tree is a trie keyed by path segment. A directory node owns a hash map name -> child node. A file node owns its content, stored as a list of appended pieces so that appending is cheap. Every call does the same two steps: validate and split the path, then walk segment by segment from the root. The walk only reads; it never creates. That is what enforces the strict-parent rule for free.
Contract (state it out loud first — the prompt leaves some cases open):
| Call | Success | Failure |
|---|---|---|
mkdir(p) | new empty directory | bad path, parent missing, parent is a file, name already taken, or p == "/" |
createFile(p, c) | new file with content c | same failures, plus p == "/" |
appendToFile(p, c) | content extended | path missing or points at a directory |
readFile(p) | full content string | path missing or points at a directory |
ls(p) | sorted child names, or [name] if p is a file | bad or missing path |
Raise typed errors (ValueError for malformed paths, FileNotFoundError / NotADirectoryError / FileExistsError for state problems). The choice matters less than being consistent and guaranteeing that a failed call mutates nothing.
Path validation. Require a non-empty string starting with /. "/" splits into zero segments. A trailing slash or a doubled slash yields an empty segment and is rejected. Reject . and .. so names stay literal; mention that you would resolve them if the interviewer asked for normalization.
Implementation (Python):
from typing import Dict, List, Optional
class _Node:
__slots__ = ("is_file", "children", "chunks")
def __init__(self, is_file: bool):
self.is_file = is_file
self.children: Optional[Dict[str, "_Node"]] = None if is_file else {}
self.chunks: Optional[List[str]] = [] if is_file else None
class FileSystem:
def __init__(self):
self.root = _Node(is_file=False)
@staticmethod
def _split(path: str) -> List[str]:
if not isinstance(path, str) or not path.startswith("/"):
raise ValueError(f"bad path {path!r}")
if path == "/":
return []
parts = path[1:].split("/")
if any(p in ("", ".", "..") for p in parts):
raise ValueError(f"bad path {path!r}")
return parts
def _resolve(self, parts: List[str]) -> _Node:
node = self.root
for p in parts:
if node.is_file:
raise NotADirectoryError("/" + "/".join(parts))
nxt = node.children.get(p)
if nxt is None:
raise FileNotFoundError("/" + "/".join(parts))
node = nxt
return node
def _new_parent_slot(self, path: str):
parts = self._split(path)
if not parts:
raise FileExistsError("/") # root always exists
parent = self._resolve(parts[:-1]) # read-only walk
if parent.is_file:
raise NotADirectoryError(path)
if parts[-1] in parent.children:
raise FileExistsError(path)
return parent, parts[-1]
def ls(self, path: str) -> List[str]:
parts = self._split(path)
node = self._resolve(parts)
return [parts[-1]] if node.is_file else sorted(node.children)
def mkdir(self, path: str) -> None:
parent, name = self._new_parent_slot(path)
parent.children[name] = _Node(is_file=False)
def createFile(self, path: str, content: str = "") -> None:
parent, name = self._new_parent_slot(path)
f = _Node(is_file=True)
if content:
f.chunks.append(content)
parent.children[name] = f
def appendToFile(self, path: str, content: str) -> None:
node = self._resolve(self._split(path))
if not node.is_file:
raise IsADirectoryError(path)
if content:
node.chunks.append(content)
def readFile(self, path: str) -> str:
node = self._resolve(self._split(path))
if not node.is_file:
raise IsADirectoryError(path)
if len(node.chunks) > 1: # compact: amortized cheap reads
node.chunks = ["".join(node.chunks)]
return node.chunks[0] if node.chunks else ""
Why it is correct. _resolve performs only children.get, so a missing mid-path node always surfaces as an error. Mutations write exactly one map entry, and only after every check has passed, so a raising call leaves the tree untouched. A path resolves to a node iff that node was created and all its ancestors exist — exactly the trie invariant.
Cost. With L the path length, d the depth, k the number of children listed, C content size: parsing and walking is O(L); mkdir/createFile are O(L + C); appendToFile is O(L + |content|) amortized; readFile is O(L + C) amortized thanks to the compaction step; ls is O(L + k log k) on a directory and O(L) on a file. Total space is O(N + S): one key string per node plus all stored content. Hash-map operations use average-case O(1) probes.
Scaling notes and trade-offs. If ls on huge directories dominates, keep each directory as a sorted map (or maintain a cached sorted list invalidated on insert/delete), trading O(log k) insertions for O(k) listing without the sort. Intern repeated segment strings to cut memory. For extremely large trees, shard by top-level directory across processes.
Root and invalid-path cases. ls("/") lists the top level; mkdir("/") and createFile("/") fail because root exists and can never be a file; readFile("/") fails because root is a directory; "/a/", "/a//b", and "a/b" are malformed; /a.txt/b where a.txt is a file is a not-a-directory error.
Part B — Bounded FIFO queue
Choice: ring buffer over linked list. A linked list gives O(1) operations too, but allocates a node per enqueue, follows pointers (cache misses), and needs a node freed per dequeue. A fixed array allocates once, uses exactly capacity slots, and every index calculation is a cheap modulo or branch.
Implementation:
from typing import Optional
class CircularQueue:
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self._buf = [None] * capacity
self._cap = capacity
self._head = 0 # index of front element
self._size = 0 # number of elements present
def enQueue(self, x: int) -> bool:
if self.isFull():
return False
self._buf[(self._head + self._size) % self._cap] = x
self._size += 1
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
self._buf[self._head] = None
self._head = (self._head + 1) % self._cap
self._size -= 1
return True
def Front(self) -> Optional[int]:
return None if self.isEmpty() else self._buf[self._head]
def Rear(self) -> Optional[int]:
return None if self.isEmpty() else self._buf[(self._head + self._size - 1) % self._cap]
def isEmpty(self) -> bool:
return self._size == 0
def isFull(self) -> bool:
return self._size == self._cap
Why correctness follows. Invariant: the live elements occupy the size consecutive ring slots starting at head, front first. Enqueue writes at head + size and increments size; dequeue clears the head slot, advances head, and decrements size. Both preserve the invariant, and size alone distinguishes full from empty, which is why we avoid the classic head == tail ambiguity of an index-pair design.
Cost. Every operation does a constant number of arithmetic ops, one indexed read/write, and one branch — O(1) time and exactly O(capacity) space (versus O(capacity) nodes with pointers and allocator overhead for a linked list).
Common mistakes to name. Using head == tail both for empty and full; forgetting the modulo when wrapping rear; letting a zero capacity through; storing size but computing Rear as buf[head - 1] after a wrap; and, in Part A, creating missing intermediates inside the resolver (which silently breaks the strict-parent contract) or validating paths after mutating state.