Least Recently Used (LRU) Cache, by LeetCode

I've solved an LRU from DailyCodingProblem before, but finally stumbled on one by LeetCode (#418 in my solved list), here it is: https://leetcode.com/problems/lru-cache/

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4

Same approach as I used before:

  1. Two data structures: a LIST of keys to keep track of the temporal aspect ("least"), and a HASHTABLE for quick access ("cache")
  2. On GET: check for presence in the HASHTABLE. If -ve, return -1. If +ve, move the element up to the front in the LIST and return the value in the HASHTABLE
  3. On PUT: if in the HASHTABLE, update it in the LIST accordingly and move it to the front. If not, check the capacity, if on the limit, remove the last from the LIST. Add the new element to the front of the LIST and add it to the HASHTABLE.
GET is O(1), PUT is O(1). Code is below, cheers, ACC.


public class LRUCache
{
 Hashtable htIndex = null;
 LinkedList cache = null;
 int capacity = 0;
 public LRUCache(int capacity)
 {
 this.capacity = capacity;
 htIndex = new Hashtable();
 cache = new LinkedList();
 }
 public int Get(int key)
 {
 if (!htIndex.ContainsKey(key)) return -1;
 int retVal = (int)htIndex[key];
 cache.Remove(key);
 cache.AddFirst(key);
 return retVal;
 }
 public void Put(int key, int value)
 {
 if (htIndex.ContainsKey(key))
 {
 cache.Remove(key);
 cache.AddFirst(key);
 htIndex[key] = value;
 }
 else
 {
 if (cache.Count == capacity)
 {
 int last = cache.Last.Value;
 htIndex.Remove(last);
 cache.RemoveLast();
 }
 cache.AddFirst(key);
 htIndex.Add(key, value);
 }
 //PrintCache();
 }
 private void PrintCache()
 {
 foreach (int k in cache)
 {
 Console.Write("({0},{1}) => ", k, (int)htIndex[k]);
 }
 Console.WriteLine();
 }
}

Comments

  1. love this problem! Unfortunately your implementation has linear complexity for both put and get because of cache.Remove(key) statements - a linear scan is required to do this. In C++ I store pointers to list nodes, so that removal can be done in constant time:

    class LRUCache {
    private:
    using KV = pair;
    list values;
    unordered_map::iterator> table;
    int capacity;
    public:
    LRUCache(int capacity): capacity(capacity) {}

    int get(int key) {
    auto found = table.find(key);
    if (found == table.end()) return -1;
    int value = found->second->second;
    if (found->second != values.begin()) {
    values.erase(found->second);
    values.emplace_front(key, value);
    found->second = values.begin();
    }
    return found->second->second;
    }

    void put(int key, int value) {
    auto found = table.find(key);
    if (found != table.end()) {
    if (found->second->second != value) found->second->second = value;
    if (found->second != values.begin()) {
    values.erase(found->second);
    values.emplace_front(key, value);
    found->second = values.begin();
    }
    return;
    }
    if (table.size() == capacity) {
    int key_to_evict = values.back().first;
    table.erase(key_to_evict);
    values.pop_back();
    }
    values.emplace_front(key, value);
    table[key] = values.begin();
    }
    };

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...