PracHub
QuestionsCoachesLearningGuidesInterview Prep

Quick Overview

This question evaluates skills in designing and implementing an in-memory key-value store with serialization, testing data structure design, API design (set/get/serialize/deserialize), serialization format selection, type fidelity for common Python types, and robust error handling.

  • Medium
  • OpenAI
  • Coding & Algorithms
  • Software Engineer

Implement in-memory KV store with serialization

Company: OpenAI

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: Medium

Interview Round: Technical Screen

Implement an in-memory key-value store in Python that supports setting and retrieving values and can serialize and deserialize the entire store. Define a clear API (e.g., set(key, value), get(key), serialize(), deserialize(blob)). Choose a serialization format (e.g., JSON or pickle), explain your choice, and ensure type fidelity for common Python types (ints, floats, strings, lists, dicts). Handle missing keys and malformed or incompatible serialized input gracefully. Provide basic tests to demonstrate that data round-trips correctly.

Quick Answer: This question evaluates skills in designing and implementing an in-memory key-value store with serialization, testing data structure design, API design (set/get/serialize/deserialize), serialization format selection, type fidelity for common Python types, and robust error handling.

Implement a function `solution(operations)` that simulates a small **in-memory key-value store** with a typed, JSON-backed serialization API. The store supports four operations: `set`, `get`, `serialize`, and `deserialize`. JSON is used as the serialization format because it is human-readable, portable, and safer than `pickle`. To preserve type fidelity across a serialize/deserialize round-trip, the store only accepts values built from a restricted set of types. ## What to implement `operations` is a list of operations to apply **in order**, starting from an empty store. Each operation is a sequence (e.g. a tuple) whose **first element is the command name** and whose remaining elements are that command's arguments. Return a **list with exactly one result per operation**, in the same order. ## Supported values A value is **supported** if it is one of the following (checked recursively): - an `int` - a **finite** `float` (i.e. not `NaN`, `inf`, or `-inf`) - a `str` - a `list` whose every element is supported - a `dict` whose **every key is a `str`** and whose every value is supported `bool` and `None` are **not** supported values (note that in Python `True`/`False` are `int` instances, so they must be rejected explicitly). ## Operations **`('set', key, value)`** - If `key` is a `str` **and** `value` is supported, store the value under `key` (overwriting any existing entry) and append `True`. - Otherwise append `False` and leave the store **unchanged**. **`('get', key)`** - Append the value currently stored under `key`, or `None` if the key is not present. **`('serialize',)`** - Append a **compact JSON string** of the entire store, with **keys sorted lexicographically** and no extra whitespace (use `,` and `:` as separators). Non-finite floats are never produced. The serialization of an empty store is `"{}"`. **`('deserialize', blob)`** - `blob` must be a `str` containing JSON that parses to an **object representing the whole store**. - If `blob` is a string, parses successfully as JSON, the parsed result is a `dict`, **and** that dict is supported, then **replace the entire store** with it and append `True`. - Otherwise (non-string `blob`, malformed JSON, a parsed value that is not a `dict`, or a dict containing unsupported values) append `False` and leave the store **unchanged**. ## Edge cases - Any operation whose command is unrecognized, whose argument count is wrong, or that is empty appends `False` — **except** a `get` with the wrong argument count, which appends `None`. - An empty `operations` list returns an empty list. ## Constraints - `0 <= len(operations) <= 10^4` - Store keys and all nested dict keys must be strings. - Supported stored values are `int`, finite `float`, `str`, `list`, and `dict`, with recursive nesting allowed. - The total size of all values and serialized blobs processed is at most `2 * 10^5`. ## Example ``` operations = [ ('set', 'count', 5), ('set', 'info', {'name': 'Ada', 'scores': [1, 2.5]}), ('serialize',), ('deserialize', '{"count":5,"info":{"name":"Ada","scores":[1,2.5]}}'), ('get', 'info'), ] # returns: # [True, # True, # '{"count":5,"info":{"name":"Ada","scores":[1,2.5]}}', # True, # {'name': 'Ada', 'scores': [1, 2.5]}] ```

Constraints

  • 0 <= len(operations) <= 10^4
  • Store keys and all nested dict keys must be strings
  • Supported stored values are int, finite float, str, list, and dict with recursive nesting
  • The total size of all values and serialized blobs processed is at most 2 * 10^5

Examples

Input: [('set', 'count', 5), ('set', 'info', {'name': 'Ada', 'scores': [1, 2.5]}), ('serialize',), ('deserialize', '{"count":5,"info":{"name":"Ada","scores":[1,2.5]}}'), ('get', 'info')]

Expected Output: [True, True, '{"count":5,"info":{"name":"Ada","scores":[1,2.5]}}', True, {'name': 'Ada', 'scores': [1, 2.5]}]

Explanation: Two values are stored, the whole store is serialized to deterministic JSON, deserialized back, and the nested object is retrieved unchanged.

Input: [('set', 'x', [1, 2, 3]), ('get', 'missing'), ('deserialize', '{"x":[1,2,3]'), ('get', 'x')]

Expected Output: [True, None, False, [1, 2, 3]]

Explanation: Getting a missing key returns None. The malformed JSON blob fails to deserialize, so the previous store remains intact.

Input: [('set', 'obj', {1: 'a'}), ('serialize',), ('get', 'obj')]

Expected Output: [False, '{}', None]

Explanation: The nested dict uses a non-string key, which would lose fidelity in JSON, so set fails and the store stays empty.

Input: [('set', 'a', 1), ('deserialize', '[1,2,3]'), ('get', 'a'), ('serialize',)]

Expected Output: [True, False, 1, '{"a":1}']

Explanation: The blob is valid JSON but incompatible because the store must deserialize from a JSON object, not a list.

Input: []

Expected Output: []

Explanation: No operations means no results.

Hints

  1. Use a normal dictionary for the live store, and write one recursive helper that validates whether a value can be safely serialized without losing type information.
  2. Make serialization deterministic by sorting keys and removing extra whitespace, so exact string comparisons in tests are stable.
Last updated: Apr 30, 2026

Loading coding console...

PracHub

Master your tech interviews with 8,000+ real questions from top companies.

Product

  • Questions
  • Learning Tracks
  • Interview Guides
  • Resources
  • Premium
  • For Universities
  • Student Access

Browse

  • By Company
  • By Role
  • By Category
  • Topic Hubs
  • SQL Questions
  • AI Coding Questions
  • Compare Platforms
  • Discord Community

Support

  • support@prachub.com
  • (916) 541-4762

Legal

  • Privacy Policy
  • Terms of Service
  • About Us

© 2026 PracHub. All rights reserved.

Related Coding Questions

  • Infection Spread Simulation with Death Threshold - OpenAI (medium)
  • Spreading Contagion on a Grid - OpenAI (medium)
  • Streaming Entropy with Numerical Stability - OpenAI (hard)
  • Implement a Distributed Rate Limiter - OpenAI (medium)
  • Compute Plant Infection Time - OpenAI (medium)