00:00

Problem Statement

Input/Output Examples

Visual Explanation

Expiry here is lazy: a stale entry is removed when someone looks it up, or when it becomes the least recently used one.

Approaches

Both approaches pass the same 5,000 random test runs. The first builds on LinkedHashMap; the second writes the linked list by hand.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Every operation is a hash lookup plus a few pointer changes. Memory holds at most capacity entries, each with one extra timestamp.

Interview Tips and Recommended Approach

  • Inject the clock. Passing the time in (or a Clock) makes TTL logic testable without sleeping.
  • Mention active cleanup. Lazy expiry can keep stale entries; a scheduled sweep or a priority queue of expiry times removes them early.
  • Synchronise for threads. LinkedHashMap is not thread-safe, and even a get changes it in access order.
  • Know the libraries: Caffeine offers expireAfterWrite() and size limits ready-made.

Recommended Approach: LinkedHashMap in Access Order

Why: it is short, correct and built on a well-tested JDK class. Write the manual list when the interviewer rules LinkedHashMap out.