FastPrepThread-Safe LRU Cache with TTL
Problem · Design

Thread-Safe LRU Cache with TTL

Learn this problem
HardLinkedIn logoLinkedInFULLTIMEONSITE INTERVIEW

Problem statement

Simulate a fixed-capacity least recently used cache whose entries also expire. You receive a capacity, parallel operation names, and integer argument rows. Process operations atomically in the supplied order.

  • PUT uses [time,key,value,ttl]. It stores or replaces the key, which expires at time + ttl, and makes the key most recent. Produce "null".
  • GET uses [time,key]. Produce the stored value as a decimal string and make the key most recent, or produce "-1" when absent.

Times are nondecreasing. Before every operation, remove all keys whose expiration time is less than or equal to the current time. Remove expired keys before deciding whether a PUT needs LRU eviction. A non-positive capacity stores nothing.

Return one output string for every operation. The sequence represents a legal linearization of concurrent calls, so each operation must observe and update one complete cache state.

Function

runLRUWithTTL(capacity: int, operations: String[], arguments: int[][]) → String[]

Examples

Example 1

capacity = 2operations = ["PUT","PUT","GET","PUT","GET","GET"]arguments = [[0,1,10,5],[1,2,20,10],[2,1],[6,3,30,5],[6,1],[7,2]]return = ["null","null","10","null","-1","20"]

Key 1 expires at time 5, so it is removed before the PUT at time 6. Key 2 remains live.

Example 2

capacity = 1operations = ["PUT","PUT","GET","PUT","GET"]arguments = [[0,5,7,3],[2,5,9,10],[4,5],[5,6,1,10],[6,5]]return = ["null","null","9","null","-1"]

The second PUT replaces key 5 and extends its TTL. Inserting key 6 later evicts key 5 from the capacity-one cache.

Constraints

  • -100000 <= capacity <= 100000.
  • 1 <= operations.length == arguments.length <= 100000.
  • Each operation is exactly PUT or GET and has the stated argument count.
  • -10^9 <= key, value <= 10^9.
  • 0 <= time <= 10^9, times are nondecreasing, and 1 <= ttl <= 10^9.
  • The sum time + ttl fits in a signed 64-bit integer.

More LinkedIn problems

drafts saved locally
public String[] runLRUWithTTL(int capacity, String[] operations, int[][] arguments) {
    // Write your solution here.
}
capacity2
operations["PUT","PUT","GET","PUT","GET","GET"]
arguments[[0,1,10,5],[1,2,20,10],[2,1],[6,3,30,5],[6,1],[7,2]]
expected["null", "null", "10", "null", "-1", "20"]
checking account