Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

LRU Cache With TTL Eviction

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is LRU Cache With TTL Eviction. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Implement an LRU cache with TTL support. The cache must evict the least recently used item when it reaches capacity, and it must also treat expired items as missing.

You are given a sequence of operations to apply to the cache. Each operation is either put(key, value, ttl, current_time) or get(key, current_time). A put stores key with value and an expiration time of current_time + ttl. A get returns the stored value if the key exists and has not expired at current_time, otherwise it returns -1.

Formal specification

Implement: def lru_cache_ttl(capacity, operations):

  • capacity is an integer, the maximum number of unexpired entries the cache can hold.
  • operations is a list of operations, where each operation is a list:
    • ['put', key, value, ttl, current_time]
    • ['get', key, current_time]
  • Return a list of results for all get operations, in order.

Use current_time as an integer timestamp. An item is expired when current_time >= expire_time.

Constraints

  • 1 <= capacity <= 10^4
  • 1 <= len(operations) <= 10^4
  • 0 <= key, value <= 10^9
  • 1 <= ttl <= 10^9
  • 0 <= current_time <= 10^9
  • current_time values are nondecreasing across operations

Function Signature

def lru_cache_ttl(capacity, operations):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output