KatInterview

Snapshot and Restore for an In-Memory String Map

Data Structure DesignModel answer
MediumModel answerData Structure Designserializationbinary-formathash-map

Last updated

Build an in-memory string map in C++ that can dump its full state to a byte buffer and rebuild it, handling arbitrary bytes, corrupt input, and failed restores safely.

Design and implement, in C++, a small in-memory map from string keys to string values that can be saved to a byte buffer and restored from one.

Required operations

  • put(key, value): insert or replace the value for key.
  • get(key): return the value as an optional<string>, or nullopt if the key is absent.
  • erase(key): remove the key. Erasing a missing key does nothing.
  • serialize(): return a vector<uint8_t> that captures the entire current contents.
  • deserialize(const vector<uint8_t>&): replace the contents of the store with the state described by the buffer, so that the restored store is indistinguishable from the one that was saved.

Constraints

  • Use only the byte I/O helpers you are given (read/write of fixed-width integers and raw byte runs). No external serialization libraries.
  • The format must be binary, versioned and length-prefixed. Keys and values may contain any bytes (including \0, newlines and arbitrary UTF-8).
  • Behave correctly for an empty store, very large keys or values, repeated overwrites and deletions.
  • Malformed, truncated or hostile input must be detected and reported with a clear error, not crash or allocate unbounded memory.
  • Time and space for serialize and deserialize should be O(n) in the total serialized size, and the encoding should work with a forward-only (streaming) reader and writer.

What to deliver

  1. The class and the byte layout you chose.
  2. Unit tests covering the edge cases above.
  3. A discussion of complexity, why you prefer length prefixes over delimiter-based text, and what happens to the store when a restore fails.

Hints

Hint 1

The map itself is easy (a hash map). Spend your effort on the byte layout: what must a reader know before it can safely consume each field?

Hint 2

Prefix every key and value with a fixed-width length instead of using a separator. Then no content can be mistaken for structure, and no escaping is needed. Add a magic number and a version field at the front.

Hint 3

On restore, never trust a number from the stream. Check that each requested length fits in the remaining bytes before reading or allocating, and parse into a temporary map that you swap in only after everything validated.