Skip to content

refactor: Enhance docs, add more tests in LFUCache #5949

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@
/**
* The {@code LFUCache} class implements a Least Frequently Used (LFU) cache.
* An LFU cache evicts the least frequently used item when the cache reaches its capacity.
* It keeps track of how many times each item is used and maintains a doubly linked list
* for efficient addition and removal of items based on their frequency of use.
* It maintains a mapping of keys to nodes, where each node contains the key, its associated value,
* and a frequency count that tracks how many times the item has been accessed. A doubly linked list
* is used to efficiently manage the ordering of items based on their usage frequency.
*
* @param <K> The type of keys maintained by this cache.
* @param <V> The type of mapped values.
* <p>This implementation is designed to provide O(1) time complexity for both the {@code get} and
* {@code put} operations, which is achieved through the use of a hashmap for quick access and a
* doubly linked list for maintaining the order of item frequencies.</p>
*
* <p>
* Reference: <a href="https://en.wikipedia.org/wiki/Least_frequently_used">LFU Cache - Wikipedia</a>
* </p>
*
* @param <K> The type of keys maintained by this cache.
* @param <V> The type of mapped values.
*
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
*/
public class LFUCache<K, V> {
Expand Down Expand Up @@ -75,7 +80,7 @@ public LFUCache(int capacity) {

/**
* Retrieves the value associated with the given key from the cache.
* If the key exists, the node's frequency is increased and the node is repositioned
* If the key exists, the node's frequency is incremented, and the node is repositioned
* in the linked list based on its updated frequency.
*
* @param key The key whose associated value is to be returned.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.thealgorithms.datastructures.caches;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

Expand All @@ -22,15 +24,15 @@ void testLFUCacheWithIntegerValueShouldPass() {
lfuCache.put(6, 60);

// will return null as value with key 2 is now evicted
assertEquals(null, lfuCache.get(2));
assertNull(lfuCache.get(2));

// should return 60
assertEquals(60, lfuCache.get(6));

// this operation will remove value with key as 3
lfuCache.put(7, 70);

assertEquals(null, lfuCache.get(2));
assertNull(lfuCache.get(2));
assertEquals(70, lfuCache.get(7));
}

Expand All @@ -41,7 +43,7 @@ void testLFUCacheWithStringValueShouldPass() {
lfuCache.put(2, "Beta");
lfuCache.put(3, "Gamma");
lfuCache.put(4, "Delta");
lfuCache.put(5, "Eplison");
lfuCache.put(5, "Epsilon");

// get method call will increase frequency of key 1 by 1
assertEquals("Alpha", lfuCache.get(1));
Expand All @@ -50,33 +52,87 @@ void testLFUCacheWithStringValueShouldPass() {
lfuCache.put(6, "Digamma");

// will return null as value with key 2 is now evicted
assertEquals(null, lfuCache.get(2));
assertNull(lfuCache.get(2));

// should return string Digamma
assertEquals("Digamma", lfuCache.get(6));

// this operation will remove value with key as 3
lfuCache.put(7, "Zeta");

assertEquals(null, lfuCache.get(2));
assertNull(lfuCache.get(2));
assertEquals("Zeta", lfuCache.get(7));
}

/**
* test addNodeWithUpdatedFrequency method
* @author yuluo
*/
@Test
void testAddNodeWithUpdatedFrequency() {
void testUpdateValueShouldPreserveFrequency() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(3);
lfuCache.put(1, "beijing");
lfuCache.put(2, "shanghai");
lfuCache.put(3, "gansu");
lfuCache.put(1, "A");
lfuCache.put(2, "B");
lfuCache.put(3, "C");

assertEquals("beijing", lfuCache.get(1));
assertEquals("A", lfuCache.get(1)); // Accessing key 1
lfuCache.put(4, "D"); // This should evict key 2

lfuCache.put(1, "shanxi");
assertNull(lfuCache.get(2)); // Key 2 should be evicted
assertEquals("C", lfuCache.get(3)); // Key 3 should still exist
assertEquals("A", lfuCache.get(1)); // Key 1 should still exist

assertEquals("shanxi", lfuCache.get(1));
lfuCache.put(1, "Updated A"); // Update the value of key 1
assertEquals("Updated A", lfuCache.get(1)); // Check if the update was successful
}

@Test
void testEvictionPolicyWhenFull() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(2);
lfuCache.put(1, "One");
lfuCache.put(2, "Two");

assertEquals("One", lfuCache.get(1)); // Access key 1
lfuCache.put(3, "Three"); // This should evict key 2 (least frequently used)

assertNull(lfuCache.get(2)); // Key 2 should be evicted
assertEquals("One", lfuCache.get(1)); // Key 1 should still exist
assertEquals("Three", lfuCache.get(3)); // Check if key 3 exists
}

@Test
void testGetFromEmptyCacheShouldReturnNull() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(3);
assertNull(lfuCache.get(1)); // Should return null as the cache is empty
}

@Test
void testPutNullValueShouldStoreNull() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(3);
lfuCache.put(1, null); // Store a null value

assertNull(lfuCache.get(1)); // Should return null
}

@Test
void testInvalidCacheCapacityShouldThrowException() {
assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(0));
assertThrows(IllegalArgumentException.class, () -> new LFUCache<>(-1));
}

@Test
void testMultipleAccessPatterns() {
LFUCache<Integer, String> lfuCache = new LFUCache<>(5);
lfuCache.put(1, "A");
lfuCache.put(2, "B");
lfuCache.put(3, "C");
lfuCache.put(4, "D");

assertEquals("A", lfuCache.get(1)); // Access 1
lfuCache.put(5, "E"); // Should not evict anything yet
lfuCache.put(6, "F"); // Evict B

assertNull(lfuCache.get(2)); // B should be evicted
assertEquals("C", lfuCache.get(3)); // C should still exist
assertEquals("D", lfuCache.get(4)); // D should still exist
assertEquals("A", lfuCache.get(1)); // A should still exist
assertEquals("E", lfuCache.get(5)); // E should exist
assertEquals("F", lfuCache.get(6)); // F should exist
}
}