Implement KV store serialization
Company: OpenAI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates skills in binary serialization and deserialization, data encoding and layout, type tagging, endianness, checksumming, versioning for forward/backward compatibility, and algorithmic efficiency and space usage for an in-memory key-value store; it falls under the Coding & Algorithms domain.
Constraints
- All keys are strings, all strings are UTF-8, and all integers fit in signed 64-bit range.
- Serialize entries in the dict's existing iteration order; do not sort keys.
- The total serialized size is at most 10^6 bytes, and nesting depth is at most 100.
- Within a map, keys are unique.
Examples
Input: ('encode', {})
Expected Output: b'KVSB\x01\x04\x00\x00\x00\x00\x00\x00\x00;\x01\x00\x00'
Explanation: An empty map body is just a 4-byte entry count of 0. The checksum is the sum of the header and body bytes modulo 2^32.
Input: ('decode', b'KVSB\x01\x04\x00\x00\x00\x00\x00\x00\x00;\x01\x00\x00')
Expected Output: {}
Explanation: This is the valid encoding of an empty root map, so decoding returns an empty dict.
Hints
- Give every value a type tag and a length prefix. That makes recursive decoding simpler and leaves room for future type tags.
- While decoding, keep one index into the buffer and advance it carefully. For nested maps, decode only within the subrange described by that value's length.