Class LRUCache<K, V>

LRU (Least Recently Used) Cache data structure

A cache that stores key-value pairs with a fixed capacity. When the cache is full, it evicts the least recently used item.

Time Complexity:

  • get: O(1)
  • put: O(1)

Example

const cache = new LRUCache<number, string>(2);
cache.put(1, 'one');
cache.put(2, 'two');
cache.get(1); // 'one'
cache.put(3, 'three'); // evicts key 2
cache.get(2); // null
cache.get(3); // 'three'

Type Parameters

  • K

  • V

Hierarchy

  • LRUCache

Constructors

  • Creates a new LRU Cache with the specified capacity

    Type Parameters

    • K

    • V

    Parameters

    • capacity: number

      Maximum number of items the cache can hold

    Returns LRUCache<K, V>

Properties

cache: Map<K, LRUNode<K, V>>
capacity: number
head: null | LRUNode<K, V>
tail: null | LRUNode<K, V>

Methods

  • Removes a key from the cache

    Parameters

    • key: K

      The key to remove

    Returns boolean

    true if the key was removed, false if it didn't exist

  • Gets the value associated with the key Marks the key as recently used

    Parameters

    • key: K

      The key to look up

    Returns null | V

    The value associated with the key, or null if not found

  • Checks if a key exists in the cache Does not mark the key as recently used

    Parameters

    • key: K

      The key to check

    Returns boolean

    true if the key exists, false otherwise

  • Returns an array of all keys in the cache, ordered from most to least recently used

    Returns K[]

    Array of keys

  • Moves a node to the front of the list (most recently used position)

    Parameters

    • node: LRUNode<K, V>

    Returns void

  • Puts a key-value pair into the cache If the key already exists, updates the value If the cache is at capacity, evicts the least recently used item

    Parameters

    • key: K

      The key to store

    • value: V

      The value to store

    Returns void

  • Returns an array of all values in the cache, ordered from most to least recently used

    Returns V[]

    Array of values

Generated using TypeDoc