Add TTL Support

Step 3 β€” Add TTL Support

Time-to-live is what separates a dict from an actual cache. Add:

  • put(key, value, ttl_seconds=None) β€” if ttl_seconds is set, the key expires after that many seconds
  • get(key) β€” should return None (and delete the key) if it has expired
  • ttl(key) β€” return remaining seconds, or -1 if no TTL, or -2 if the key is missing

This mirrors how Redis exposes TTL.

Hints
Starter code
import time

class KeyValueStore:
    def __init__(self):
        self._store = {}

    def put(self, key, value, ttl_seconds=None):
        """Store a key-value pair with optional TTL."""
        # TODO: Store the value together with an expiry timestamp
        # Hint: store a dict like {"value": value, "expiry": expiry_or_None}
        pass

    def get(self, key):
        """Get value. Return None if missing or expired."""
        # TODO: Check if the key exists and has not expired
        # If expired, delete it and return None
        pass

    def delete(self, key):
        if key in self._store:
            del self._store[key]
            return True
        return False

    def size(self):
        return len(self._store)

    def ttl(self, key):
        """Return remaining TTL in seconds. -1 if no TTL. -2 if key missing."""
        # TODO: Implement this
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.