DEV Community

Jaspreet singh
Jaspreet singh

Posted on

LRU Cache | HashMap + Doubly Linked List

Problem Statement

Design an LRU (Least Recently Used) Cache supporting:

get(key)

put(key,value)
Enter fullscreen mode Exit fullscreen mode

Both operations must run in:

O(1)
Enter fullscreen mode Exit fullscreen mode

Brute Force Intuition

Use:

ArrayList
Enter fullscreen mode Exit fullscreen mode

Whenever an element is accessed:

Search it.

Move it to the front.

If capacity exceeds:

Remove last element.

Complexity

  • get → O(N)
  • put → O(N)

Moving Towards the Optimal Approach

We need:

Fast Lookup
Enter fullscreen mode Exit fullscreen mode

and

Fast Deletion / Insertion
Enter fullscreen mode Exit fullscreen mode

Use:

HashMap

+

Doubly Linked List
Enter fullscreen mode Exit fullscreen mode

Pattern Recognition

Need O(1) Lookup

+

Need O(1) Update

=> HashMap + DLL
Enter fullscreen mode Exit fullscreen mode

Key Observation

HashMap:

key

↓

Node Address
Enter fullscreen mode Exit fullscreen mode

DLL stores usage order.

Most Recently Used:

Front
Enter fullscreen mode Exit fullscreen mode

Least Recently Used:

Back
Enter fullscreen mode Exit fullscreen mode

Operations

get()

Found ?

↓

Move Node to Front

↓

Return Value
Enter fullscreen mode Exit fullscreen mode

put()

Already Exists?

Update

Move Front
Enter fullscreen mode Exit fullscreen mode

Else:

Insert Front
Enter fullscreen mode Exit fullscreen mode

If capacity exceeded:

Remove Tail
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Operation Complexity
Get O(1)
Put O(1)

Interview One-Liner

Combine a HashMap for O(1) lookup and a Doubly Linked List for O(1) insertion, deletion, and eviction of the least recently used element.


Pattern Learned

Cache

+

Order Matters

=> HashMap + Doubly Linked List
Enter fullscreen mode Exit fullscreen mode

Top comments (0)