Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

LRU Cache O(1) Average

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

Your question is LRU Cache O(1) Average. 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

Google services such as Google Drive may need to evict the least recently used entries when an in-memory cache reaches capacity. Design an LRU cache that supports get and put in O(1) average time.

Implement lru_cache(capacity, operations). The cache stores integer keys and values. Each operation is either ['get', key] or ['put', key, value]. Return the results of all get operations in order. A missing key returns -1.

A successful get marks the key as most recently used. Inserting a new key also marks it as most recently used. Updating an existing key changes its value and marks it as most recently used. If insertion exceeds capacity, evict the least recently used key.

Formal Specification

  • Input: capacity, a positive integer, and operations, a list of operation lists.
  • Output: A list of integer values produced by get operations.
  • Average-time requirement: Every get and put operation must run in O(1).

Constraints

  • 1 <= capacity <= 10^5
  • 1 <= len(operations) <= 2 * 10^5
  • Each operation is either ['get', key] or ['put', key, value]
  • Keys and values are integers in [-10^9, 10^9]

Function Signature

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