Understanding the Least Recently Used (LRU) cache algorithm is essential for acing technical interviews. This guide covers the implementation of LRU cache and a function to insert an integer into a sorted circular linked list. We will also provide test cases and explanations to solidify your understanding.
The Least Recently Used (LRU) cache algorithm removes the least recently used element when the cache is full. If a requested element is not found in the cache, it results in a cache miss. Your task is to implement a function that calculates the number of cache misses for a given list of integers.
int lruCountMiss(int max_cache_size, int *pages, int len);
Input:
max_cache_size = 3
pages = [7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0]
len = 16
Expected Output:
11
Input:
max_cache_size = 2
pages = [2,3,1,3,2,1,4,3,2]
len = 9
Expected Output:
8
Each time an element is not found in the cache, a cache miss occurs. The cache follows the Least Recently Used replacement policy to manage entries efficiently.
Write a function to insert an integer into a circular linked list where elements are sorted in ascending order. The function should return a pointer to the newly inserted node.
struct CNode {
int value;
CNode* next;
};
CNode* insertSortedList(CNode* start, int n);
Input:
List: [3 → 4 → 6 → 1 → 2 → ^]
n = 5
Expected Output:
[5 → 6 → 1 → 2 → 3 → 4 → ^]
Input:
List: [1 → 2 → 3 → 4 → 5 → ^]
n = 0
Expected Output:
[0 → 1 → 2 → 3 → 4 → 5 → ^]
The new node should be inserted in the correct position while maintaining the sorted order. If the list is empty, the new node should become the head.
Mastering the LRU cache algorithm and linked list operations is crucial for technical interviews. By understanding these concepts and practicing their implementation, you will be well-prepared to tackle similar problems efficiently.