Skip to content

Instantly share code, notes, and snippets.

@serdarmumcu
Created July 30, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serdarmumcu/c809833bcbe4b736dcfe8cb5bc5ece79 to your computer and use it in GitHub Desktop.
Save serdarmumcu/c809833bcbe4b736dcfe8cb5bc5ece79 to your computer and use it in GitHub Desktop.
LFU Cache Implementation Java
package com.yazilimmimari.hackerrank;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public class LFUCache<S,T> {
public class Node<S,T>
{
S key;
T value;
Integer count;
Node(S a,T b,Integer c)
{
key = a;
value = b;
count = c;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node<S, T> node = (Node<S, T>) o;
return key.equals(node.key) &&
value.equals(node.value) &&
count.equals(node.count);
}
@Override
public int hashCode() {
return Objects.hash(key, value, count);
}
}
LinkedHashMap<S,Node<S,T>> cache;
int capacity;
public LFUCache(int capacity)
{
this.capacity = capacity;
this.cache = new LinkedHashMap<>(capacity);
}
public void put(S key, T value)
{
if (cache.containsKey(key)) {
Node<S, T> node = cache.get(key);
cache.remove(key);
node.value = value;
node.count++;
cache.put(key,node);
return;
}
if(isFull())
{
if(this.capacity == 0)
return;
S minKey = null;
int minFreq = Integer.MAX_VALUE;
for(Map.Entry<S,Node<S,T>> entry: cache.entrySet())
{
if(minFreq > entry.getValue().count)
{
minFreq = entry.getValue().count;
minKey = entry.getKey();
}
}
cache.remove(minKey);
}
Node<S, T> newNode = new Node<S, T>(key, value, 0);
cache.put(key, newNode);
}
public T get(S key)
{
if(cache.containsKey(key)) // cache hit
{
Node<S,T> node = cache.get(key);
node.count++;
cache.remove(key);
cache.put(key,node);
return node.value;
}
return null; // cache miss
}
public boolean isFull()
{
if(this.cache.size() == this.capacity)
return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment