Practice/Microsoft/Design a key-value store
Object Oriented DesignMust
Design and implement an in-memory caching system that efficiently stores and retrieves data with configurable eviction policies. Your cache must support multiple data types (strings, numbers, lists) and handle automatic expiration of items based on time-to-live (TTL) values or capacity constraints.
The system should support three eviction strategies:
Your implementation should handle edge cases like concurrent access patterns, expired items, and capacity limits gracefully.
CacheSystem class that accepts a maximum capacity and eviction policyset(), get(), and delete() for key-value pairsset_list(), get_list(), and list_append() methodsExample 1: Basic Operations
` cache = CacheSystem(capacity=3) cache.set("name", "John") cache.set("age", 30) cache.set("city", "NYC")
print(cache.get("name")) # Output: "John" print(cache.get("age")) # Output: 30 `
Example 2: LRU Eviction
` cache = CacheSystem(capacity=2, eviction_policy="LRU") cache.set("a", 1) cache.set("b", 2) cache.get("a") # Access "a", making it recently used cache.set("c", 3) # This evicts "b" since it's least recently used
print(cache.get("b")) # Output: None (evicted) print(cache.get("a")) # Output: 1 (still present) `
Example 3: TTL Expiration
` cache = CacheSystem(capacity=5) cache.set("session", "abc123", ttl=2) # Expires in 2 seconds
print(cache.get("session")) # Output: "abc123" time.sleep(3) print(cache.get("session")) # Output: None (expired) `
Example 4: List Operations
` cache = CacheSystem(capacity=10) cache.set_list("tasks", ["task1", "task2"]) cache.list_append("tasks", "task3")
print(cache.get_list("tasks")) # Output: ["task1", "task2", "task3"] `