1. Array with Linear Search and Timestamps
Intuition
Store all cache elements in an array where each record contains (key, value, timestamp).
- get(key): Linear scan through the array for key. If found, increment global timestamp, update record timestamp, and return value. Else return -1.
- put(key, value): Linear scan. If key found, update value and timestamp. If absent and capacity full, scan to find record with minimal timestamp, remove it, and append new entry.
Scanning requires O(C) time per operation where C is capacity.
When to apply: Basic prototyping where capacity is very small.
Algorithm
- Step 1: Maintain an array of { key, value, time } objects and an auto-incrementing timer.
- Step 2: On get, iterate through array to locate key. Update time and return value if found, else -1.
- Step 3: On put, locate key. If found, update value and time.
- Step 4: If key is new and size == capacity, scan to find index with min time and erase it.
- Step 5: Push new entry with updated time.
#include <iostream>#include <vector> struct Item { int key, value, time;}; class LRUCacheBrute { int capacity; int timer = 0; std::vector<Item> cache;public: LRUCacheBrute(int cap) : capacity(cap) {} int get(int key) { for (auto& item : cache) { if (item.key == key) { item.time = ++timer; return item.value; } } return -1; } void put(int key, int value) { for (auto& item : cache) { if (item.key == key) { item.value = value; item.time = ++timer; return; } } if ((int)cache.size() >= capacity) { int lruIdx = 0; for (int i = 1; i < (int)cache.size(); ++i) { if (cache[i].time < cache[lruIdx].time) { lruIdx = i; } } cache.erase(cache.begin() + lruIdx); } cache.push_back({key, value, ++timer}); }}; int main() { LRUCacheBrute lru(2); lru.put(1, 1); lru.put(2, 2); std::cout << lru.get(1) << std::endl; lru.put(3, 3); std::cout << lru.get(2) << std::endl; lru.put(4, 4); std::cout << lru.get(1) << std::endl; std::cout << lru.get(3) << std::endl; std::cout << lru.get(4) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(C) for get and put where C is cache capacity - Space complexity:
O(C) auxiliary space