Implement a Map with Time Expiration (Heap/Set)

Data Structures
Hard
Apple
57.3K views

Design a map where keys expire after a specified duration. Use a combination of a Hash Map for storage and a Min-Heap for managing expiration times efficiently.

Why Interviewers Ask This

Apple evaluates this question to assess your ability to balance space-time trade-offs in real-world caching scenarios. They specifically test if you can design a system that handles concurrent expiration efficiently without blocking operations, ensuring high availability and low latency for features like session management or temporary data storage.

How to Answer This Question

1. Clarify requirements immediately: ask about concurrency, whether eviction happens on access or write, and expected load patterns. 2. Propose the dual-structure solution: a Hash Map for O(1) key lookups and a Min-Heap storing (timestamp, key) pairs for efficient expiration checks. 3. Explain the insertion logic: update the map and push the new timestamp to the heap, handling duplicates lazily. 4. Detail the get/put operation: perform lazy cleanup by popping expired entries from the heap top before returning values. 5. Discuss complexity analysis rigorously, noting that while get is amortized O(log N), worst-case cleanup could be expensive, suggesting a background thread or scheduled task as an optimization Apple would appreciate.

Key Points to Cover

  • Explicitly mention the O(1) lookup benefit of the Hash Map
  • Explain the lazy deletion strategy to avoid unnecessary heap traversals
  • Address the handling of duplicate updates for the same key
  • Analyze the time complexity trade-off between immediate vs. lazy cleanup
  • Demonstrate awareness of Apple's emphasis on performance and resource optimization

Sample Answer

To implement a time-expiring map, I would combine a Hash Map with a Min-Heap. The Hash Map stores the actual key-value pairs for O(1) retrieval, while the Min-Heap tracks the expiration timestamps paired with keys, allow…

Common Mistakes to Avoid

  • Forgetting to handle duplicate keys in the heap, leading to stale entries remaining after deletion
  • Attempting to clean up all expired items on every single insert or get call, causing O(N) latency
  • Ignoring the need to store the original key in the heap alongside the timestamp for removal
  • Failing to define what happens when a key is updated with a new expiration time

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 166 Data Structures questionsBrowse all 54 Apple questions