Quick Overview

This question evaluates a candidate's ability to design and implement efficient data structures that meet strict O(1) time constraints while managing access-based eviction policies, testing competencies in algorithmic reasoning, state management, and performance trade-offs.

Implement an LRU cache

Company: Oracle

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

Design and implement an in-memory cache that evicts entries using the **Least Recently Used (LRU)** policy. The cache should store key–value pairs and support the following operations: - `LRUCache(int capacity)`: Initialize the cache with a positive integer `capacity` representing the maximum number of key–value pairs it can hold. - `int get(int key)`: - If the key exists in the cache, return its value and mark this key as **most recently used**. - If the key does not exist, return `-1`. - `void put(int key, int value)`: - Insert or update the value of the given key. - When inserting a new key causes the number of items to exceed `capacity`, you must **evict exactly one key–value pair: the one that has been least recently used** (i.e., the one whose `get` or `put` was accessed furthest in the past). - Updating an existing key should also mark it as **most recently used**. **Requirements:** - All `get` and `put` operations must run in **O(1)** average time. - You may assume: - Keys and values are integers. - `capacity >= 1`. Describe the data structures you would use and then implement the LRU cache in a language of your choice.

Quick Answer: This question evaluates a candidate's ability to design and implement efficient data structures that meet strict O(1) time constraints while managing access-based eviction policies, testing competencies in algorithmic reasoning, state management, and performance trade-offs.

Simulate an LRU cache. put inserts or updates a key and get returns the value or -1 while marking the key recently used. Return one output per operation, using None for put.

Constraints

  • Inputs are provided as Python literals matching the function signature.
  • Return a deterministic exact-match result.

Examples

Input: (2, [['put',1,1], ['put',2,2], ['get',1], ['put',3,3], ['get',2], ['put',4,4], ['get',1], ['get',3], ['get',4]])

Expected Output: [None, None, 1, None, -1, None, -1, 3, 4]

Explanation: Eviction sequence.

Input: (1, [['put',2,1], ['put',2,2], ['get',2], ['put',3,3], ['get',2]])

Expected Output: [None, None, 2, None, -1]

Explanation: Update existing key.

Hints

  1. Choose a representation that makes the core operation simple.
  2. Handle empty and boundary inputs before the main algorithm.

Loading coding console...