KatInterview

Build a Path-Addressed Tree Store and a Bounded Ring Buffer

Data Structure DesignModel answer
MediumModel answerData Structure Designtriehash-mapcircular-buffer

Last 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 /a does not exist, and createFile("/a/b/c.txt", ...) fails when /a/b does not exist.
  • ls on a directory returns its immediate children's names sorted ascending; ls on 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.