KatInterview

Expiring Store, Reversible Actions, and Org Chart Walk

Data Structure DesignModel answer
MediumModel answerData Structure Designcachettlmin-heap

Last updated

Three short design-and-code tasks: a key-value store with per-entry lifetimes and background pruning, an action history with undo/redo, and a depth-first walk over a hierarchy.

Answer all three parts. For each one, define a clean interface, write the core logic, and explain the time and space complexity.

Part 1: Key-value store with expiring entries

Build an in-memory store where every entry lives for a fixed number of seconds.

  • put(key, value, ttlSeconds) saves the value together with the moment it should stop being valid.
  • get(key) returns the value if the key is present and still valid. Otherwise it returns null (or an equivalent "missing" result).
  • Begin with the simplest implementation that is correct.

Follow-up:

  • Entries that expire but are never read again should still be removed eventually.
  • get is the hot path, so it must not do expensive housekeeping.
  • Assume a background worker or sidecar process can do the pruning. Which data structures should it use, and how does it cope with a key being overwritten?
  • State the complexity of put, get, and the pruning step.

Part 2: Reversible actions

Build a manager for actions that can be undone. Each action object has execute() and undo().

  • executeCommand(command) runs the action and records it in history only when the run succeeds.
  • undo() reverts the most recent action that is still in effect.
  • Specify what happens when there is nothing to undo.
  • Give time and space complexity.

Optional follow-up: add redo().

Part 3: Walking an org chart

An organization is a rooted tree. Each node has an id and zero or more children. Return the ids in depth-first order.

  • Use either recursion or an explicit stack.
  • Handle an empty tree.
  • Give time and space complexity.

Hints

Hint 1

For the store, a hash map from key to (value, expiry) is enough for correctness if `get` compares the expiry with the current time. The heap is only needed to reclaim memory for keys nobody reads again.

Hint 2

A min-heap keyed by expiry time lets the pruner look only at the earliest deadlines. When a key is overwritten, the old heap record becomes outdated, so before deleting, check that the record's expiry matches what the map currently holds.

Hint 3

For undo/redo, think of two stacks: one for applied commands and one for undone commands. Decide what happens to the second stack when a brand-new command is executed, and what to do if `undo()` itself throws.

Hint 4

For the tree walk, an iterative version pushes children onto a stack in reverse order so the leftmost child is visited first. An empty input should produce an empty list.