Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Hash Map / Set High frequency Solution Available Practice Mode

LRU Cache LeetCode Solution

Tags: #Hash Table #Linked List #Design

Approach Summary

HashMap + doubly-linked list. Map stores key → node; list keeps usage order (head = MRU, tail = LRU). O(1) get and put.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Hash Map / Set Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Hash Map / Set pattern.

Framework: Hash Map / Set • Interview Prep: Tested at FAANG • Explore all Hash Map / Set problems & invariants →

How to Recognize This Pattern

  • "Design a cache with O(1) get/put and eviction"
  • Ordered hash map or manual DLL + map

Complexity Analysis

Time Complexity

O(1)

Space Complexity

O(capacity)

Tags

Hash Table Linked List Design

Frequently Asked Questions

What is the optimal time and space complexity for LRU Cache?
The optimal solution for LRU Cache achieves O(1) runtime complexity and requires O(capacity) auxiliary space. Time Complexity is get(int key) is O(1) because the algorithm processes elements efficiently in linear or logarithmic scans without unnecessary nested operations. Space Complexity is O(capacity) as minimal extra memory is required beyond standard pointers or state tracking.
How do I identify that LRU Cache requires the Hash Map / Set pattern?
In technical interviews, look for key problem signals: "Design a cache with O(1) get/put and eviction"; Ordered hash map or manual DLL + map. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Hash Map / Set strategy.
What critical edge cases must be handled in LRU Cache?
Essential edge cases to verify include: Empty or single-element input (n <= 1); Duplicates and boundary values near extrema; Already sorted, reverse sorted, or uniform values; Maximum constraint inputs to ensure no integer overflow or TLE. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask LRU Cache?
LRU Cache is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Microsoft, Google, Facebook, Apple, Uber, Stripe.
Buy me a coffee
Daily Practice
0/0