Magicsheet logo

Cache With Time Limit

Medium
68.4%
Updated 6/1/2025

Cache With Time Limit

What is this problem about?

The Cache With Time Limit interview question asks you to implement a data structure that stores key-value pairs with an expiration time. You need to implement methods for set(key, value, duration), get(key), and count(). If a key is accessed after its duration has passed, it should be treated as non-existent. This Cache With Time Limit coding problem is a practical exercise in asynchronous state management.

Why is this asked in interviews?

Uber, Microsoft, and Confluent use this to evaluate a candidate's familiarity with timers and object-oriented design. It tests whether you can handle overwriting existing keys (and their associated timers) and how you clean up expired data to prevent memory leaks. It’s a very common task in real-world system design for session management and caching.

Algorithmic pattern used

This doesn't use a specific "LeetCode pattern" but relies on Object-Oriented Design and Timers. You typically use a Map to store the data and a separate mechanism (like setTimeout in JavaScript or a Priority Queue of expiration times in other languages) to invalidate keys.

Example explanation

  1. set(1, "A", 1000): Key 1 is stored. A timer for 1000ms is started.
  2. get(1) at 500ms: Returns "A".
  3. set(1, "B", 1000) at 800ms: Old timer is cleared. New value "B" is stored with a new 1000ms timer.
  4. get(1) at 2000ms: Returns -1 (expired).

Common mistakes candidates make

  • Zombie Timers: Forgetting to clear the old timer when a key is overwritten. This leads to keys expiring too early or multiple timers running for the same key.
  • Race conditions: Not handling the case where a key expires exactly as a get call is being processed.
  • Inaccurate count: Including expired keys in the active count because the cleanup process hasn't run yet.

Interview preparation tip

Practice implementing basic TTL (Time To Live) logic. Understand how your language handles asynchronous tasks—whether it's setTimeout, ScheduledExecutorService, or goroutines. Clean cleanup of resources is a hallmark of a senior engineer.

Similar Questions