KatInterview

Type-Safe Storage with Lifetime Tracking

Data Structure DesignAuto-graded · 19 test cases
HardAuto-gradedData Structure Designobject-lifetimetype-safetyexception-handling

Last updated

Tests understanding of object lifetime management, type tracking, and exception safety in a discriminated union implementation.

Problem Description

Design a type-safe storage container that holds a value of one type at a time from a fixed set of supported types. The container must track which type is currently stored and enforce correct access patterns.

Your task is to simulate the behavior of such a container by processing a sequence of operations and returning their results.

Operations

You will receive two parallel lists:

  • operations: a list of operation names
  • arguments: a list of argument lists, one per operation

The operations are:

  1. "set" with arguments [type_name, value]: Store a new value of the given type. If a value already exists, it is destroyed first. Returns null.

  2. "get" with arguments [type_name]: Retrieve the stored value if the active type matches type_name. Returns the value on success, or an error dictionary on failure.

  3. "fail_set" with arguments []: Simulates a construction failure during a set operation. The container's previous state must be preserved (strong exception guarantee). Returns an error dictionary.

Error Handling

Return error dictionaries for these cases:

  • {"error": "empty"}: Attempting to get when no value is stored
  • {"error": "type_mismatch"}: Attempting to get with the wrong type
  • {"error": "construction_failed"}: A fail_set operation was attempted

When fail_set is called, the construction fails but the old value must remain intact.

Constraints

  • 1 ≤ len(operations) ≤ 1000
  • Each operation is one of "set", "get", or "fail_set"
  • Type names are non-empty strings
  • Values can be of any type (int, string, float, etc.)
  • The container starts empty
  • Operations are processed in order, and results are collected in a list

Examples

Example 1

Input: process_variant_operations(['set', 'get', 'set', 'get'], [['int', 42], ['int'], ['string', 'hello'], ['string']])

Output: [None, 42, None, 'hello']

Example 2

Input: process_variant_operations(['get', 'set', 'get'], [['int'], ['string', 'hello'], ['int']])

Output: [{'error': 'empty'}, None, {'error': 'type_mismatch'}]

Example 3

Input: process_variant_operations(['set', 'fail_set', 'get'], [['int', 7], [], ['int']])

Output: [None, {'error': 'construction_failed'}, 7]

Hints

Hint 1

Track both the currently active type name and its value; use None to represent an empty state

Hint 2

When fail_set is called, it should raise an exception without modifying the container's current state

Hint 3

Remember that get must validate both that the container is non-empty and that the requested type matches the stored type