Type-Safe Storage with Lifetime Tracking
Data Structure DesignAuto-graded · 19 test casesLast 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 namesarguments: a list of argument lists, one per operation
The operations are:
-
"set"with arguments[type_name, value]: Store a new value of the given type. If a value already exists, it is destroyed first. Returnsnull. -
"get"with arguments[type_name]: Retrieve the stored value if the active type matchestype_name. Returns the value on success, or an error dictionary on failure. -
"fail_set"with arguments[]: Simulates a construction failure during asetoperation. 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 togetwhen no value is stored{"error": "type_mismatch"}: Attempting togetwith the wrong type{"error": "construction_failed"}: Afail_setoperation 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
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem simulates a type-safe container that enforces correct object lifetime management. The key insight is to model the container's state machine: it can be either empty or holding a value of a specific type.
The solution maintains two pieces of state:
- Active type: which type is currently stored (or
Noneif empty) - Stored value: the actual value being held
For each operation:
set: Replace the current value (if any) with a new one. This simulates destruction of the old object and construction of the new one.get: Validate that the container is non-empty and that the requested type matches the stored type. Return the value on success, or raise an appropriate exception.fail_set: Simulate a construction failure. The key property is that the old state must be preserved (strong exception guarantee), so we raise an exception without modifying any state.
Exception handling converts internal exceptions into the required error dictionary format.
Why This Works
The invariant maintained is: active_type is None if and only if the container is empty. Every successful set establishes this invariant by storing both the type and value atomically. The fail_set operation preserves this invariant by not modifying state at all.
Type safety comes from comparing the requested type name against the stored type name before allowing access. This mirrors how a real variant implementation would use runtime type information to validate access.
Complexity
- Time: O(n) where n is the number of operations. Each operation is processed in constant time.
- Space: O(1) for the container state, O(n) for the output list.
Solution Code
from typing import List
def process_variant_operations(operations: List[str], arguments: List[List[object]]) -> List[object]:
class EmptyVariantError(Exception):
pass
class TypeMismatchError(Exception):
pass
class ConstructionFailedError(Exception):
pass
class TypeSafeContainer:
def __init__(self):
self.active_type = None
self.stored_value = None
def store(self, type_name: str, value=None):
# Simulate destroying old value and storing new one
self.active_type = type_name
self.stored_value = value
def retrieve(self, type_name: str):
if self.active_type is None:
raise EmptyVariantError()
if self.active_type != type_name:
raise TypeMismatchError()
return self.stored_value
def simulate_construction_failure(self):
raise ConstructionFailedError()
container = TypeSafeContainer()
results = []
for op, args in zip(operations, arguments):
try:
if op == "set":
type_name = args[0]
value = args[1] if len(args) > 1 else None
container.store(type_name, value)
results.append(None)
elif op == "get":
type_name = args[0]
value = container.retrieve(type_name)
results.append(value)
elif op == "fail_set":
container.simulate_construction_failure()
results.append(None)
except EmptyVariantError:
results.append({"error": "empty"})
except TypeMismatchError:
results.append({"error": "type_mismatch"})
except ConstructionFailedError:
results.append({"error": "construction_failed"})
return results