KatInterview

Batch Runner for a Slash-Separated Key Store

Data Structure DesignAuto-graded · 21 test cases
MediumAuto-gradedData Structure Designdesignhash-maptrie

Last updated

Simulate a hierarchical key store from a batch of create/get commands, where a key can only be created once its parent key already exists.

Task

You are building a small in-memory store whose keys are slash-separated paths such as /a or /a/b/c. Each stored path holds one integer value.

Instead of a class, you receive a whole batch of commands and must process them in order, returning one result per command.

The store starts out empty except for the root path /. The root is considered to exist implicitly, but it never holds a value.

Commands

Each command has a name (from commands) and a list of arguments (the matching entry in params).

  • "create" with arguments [path, value]
    • Adds path to the store with the integer value and returns True.
    • Returns False, and leaves the store unchanged, if:
      • path is "/", or
      • path has already been created, or
      • the parent of path does not exist.
    • The parent of a top-level path such as /a is the root, which always exists. The parent of /a/b is /a, which must have been created earlier.
  • "get" with arguments [path]
    • Returns the integer value stored at path.
    • Returns -1 if path has not been created. This includes "/", since the root holds no value.

Nothing is ever removed or modified once created, so a failed create never changes the original value.

Output

Return a list with one entry per command, in the same order:

  • True or False for each create,
  • an integer for each get.

Constraints

  • commands and params have the same length.
  • Every command name is either "create" or "get".
  • Every path starts with /, has no trailing slash (except the root path / itself), has no empty segments, and its segments consist only of lowercase letters.
  • Values passed to create are integers.
  • Paths are compared as exact strings. Only a path that was successfully created counts as existing.

Examples

Example 1

Input: run_path_store(['create', 'get', 'create', 'get'], [['/a', 1], ['/a'], ['/a/b', 2], ['/a/b']])

Output: [True, 1, True, 2]

Example 2

Input: run_path_store(['create', 'create', 'get'], [['/a/b', 2], ['/a', 1], ['/a/b']])

Output: [False, True, -1]

Example 3

Input: run_path_store(['create', 'create', 'get', 'get'], [['/leet', 10], ['/leet/code', 20], ['/leet'], ['/leet/code']])

Output: [True, True, 10, 20]

Hints

Hint 1

Think about what must be true of a path's parent before you may add the path. How do you obtain the parent string from the path?

Hint 2

A dictionary keyed by the full path string is enough to answer both 'does this exist' and 'what is its value' in one lookup.

Hint 3

Treat the root as a special case: it is always a valid parent, but it can never be created and never returns a value, so `get('/')` yields -1.