Serialize and Split Key-Value Store Payload
Data Structure DesignAuto-graded · 25 test casesLast updated
Encodes a dictionary mapping string keys to string values into a binary protocol payload and splits it into fixed-size byte chunks.
You are tasked with persisting an in-memory key-value dictionary to a serialized binary format before saving it to storage.
To ensure deterministic output:
- Iterate over all entries in the dictionary sorted lexicographically by their string key.
- For each key-value pair, append the following four components sequentially into a raw byte stream:
- Key length: UTF-8 byte count of the key encoded as an 8-byte unsigned big-endian integer (uint64).
- Key payload: UTF-8 byte representation of the key.
- Value length: UTF-8 byte count of the value encoded as an 8-byte unsigned big-endian integer (uint64).
- Value payload: UTF-8 byte representation of the value.
- Slice the resulting byte stream into sequential chunks where each chunk contains at most
chunk_sizebytes (as integer lists). If the byte stream is empty, return an empty list.
Write a function serialize_and_chunk_store that accepts a dictionary store containing string keys and string values, along with a positive integer chunk_size, and returns a list of integer lists where each inner list represents a chunk of bytes.
Constraints
chunk_sizeis an integer such that $1 \le \text{chunk_size} \le 10^5$.- The dictionary
storecontains string keys and string values. - Keys and values may contain arbitrary Unicode characters (e.g., spaces, newlines, multi-byte UTF-8 sequences).
Output Requirements
- Each byte in the chunk lists should be represented as an integer from
0to255. - Keys must be processed in sorted order according to standard Python string ordering.
- If
storeis empty, the return value must be[].
Examples
Example 1
Input: serialize_and_chunk_store({}, 8)
Output: []
Example 2
Input: serialize_and_chunk_store({'name': 'Ada', 'city': 'New York'}, 16)
Output: [[0, 0, 0, 0, 0, 0, 0, 4, 99, 105, 116, 121, 0, 0, 0, 0], [0, 0, 0, 8, 78, 101, 119, 32, 89, 111, 114, 107, 0, 0, 0, 0], [0, 0, 0, 4, 110, 97, 109, 101, 0, 0, 0, 0, 0, 0, 0, 3], [65, 100, 97]]
Example 3
Input: serialize_and_chunk_store({'line': 'first\\nsecond', 'emoji': 'café ☕'}, 10)
Output: [[0, 0, 0, 0, 0, 0, 0, 5, 101, 109], [111, 106, 105, 0, 0, 0, 0, 0, 0, 0], [9, 99, 97, 102, 195, 169, 32, 226, 152, 149], [0, 0, 0, 0, 0, 0, 0, 4, 108, 105], [110, 101, 0, 0, 0, 0, 0, 0, 0, 13], [102, 105, 114, 115, 116, 92, 110, 115, 101, 99], [111, 110, 100]]
Hints
Hint 1
Remember to convert keys and values to UTF-8 bytes before calculating their lengths, as character count does not equal byte count for non-ASCII text.
Hint 2
Encode the length of each string as an 8-byte big-endian sequence (e.g., using `.to_bytes(8, 'big')`).
Hint 3
Concatenate all encoded records into a single byte array before partitioning it into contiguous slices of size `chunk_size`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To construct the serialized payload deterministically:
- Sort Keys: We iterate over the keys of the
storein lexicographical order usingsorted(store). - UTF-8 Encoding: For each key and value, convert the string to its UTF-8 byte representation via
.encode("utf-8"). Multi-byte characters (such as emojis or accented characters) will occupy more bytes than their string length. - Length Prefixing: Calculate the byte length of the encoded key and value, then format each length as an 8-byte big-endian integer using
.to_bytes(8, "big"). - Assembly: Append the 8-byte key length, key bytes, 8-byte value length, and value bytes sequentially into a binary buffer (
bytearray). - Chunking: Slice the complete binary buffer into chunks of size at most
chunk_size, converting each byte slice into a list of integers (0–255).
Complexity
- Time Complexity: $\mathcal{O}(N \log N + M)$, where $N$ is the number of keys in the store and $M$ is the total byte size of all encoded keys and values. Sorting takes $\mathcal{O}(N \log N)$ time and encoding/chunking takes linear time in terms of byte volume $\mathcal{O}(M)$.
- Space Complexity: $\mathcal{O}(M)$ to hold the serialized binary array and the resulting list of chunk lists.
from typing import Dict, List
def serialize_and_chunk_store(store: Dict[str, str], chunk_size: int) -> List[List[int]]:
if chunk_size <= 0:
raise ValueError("chunk_size must be positive")
data = bytearray()
for key in sorted(store):
key_bytes = key.encode("utf-8")
value_bytes = store[key].encode("utf-8")
data.extend(len(key_bytes).to_bytes(8, "big"))
data.extend(key_bytes)
data.extend(len(value_bytes).to_bytes(8, "big"))
data.extend(value_bytes)
return [list(data[i:i + chunk_size]) for i in range(0, len(data), chunk_size)]