-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
347 lines (254 loc) · 10.1 KB
/
LRUCache.java
File metadata and controls
347 lines (254 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package Algorithms.LinkedListAlgos;
import java.util.*;
/**
* consider both put and get means recent used
* evict LRU with using order or time
so how to maintain the order?
---> ArrayList by removing from the middle and adding at end -- TLE
---> LinkedHashMap with accessOrder=true --> maintain the order or access
---> Custom Doubly LinkedList by removing from the middle and adding the recent key at tail or end --> internal implementation of LinkedHashMap with accessOrder=true
---> LinkedHashMap with accessOrder=false --> remove from the middle and add to the end
---> HashMap with LinkedHashSet ---> same as above LinkedHashMap with accessOrder=false
*
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 04 Jan 2025
* @link 146. LRU Cache <a href="https://leetcode.com/problems/lru-cache/">LeetCode link</a>
* @topics Hash Table, Linked List, Design, Doubly-Linked List
* @see DataStructures.HashMapExample JavaDoc -> to understand "HOW HASHMAP WORKS"
* @companies amazon, facebook, apple, google, tiktok, oracle, palo, microsoft, goldman, bloomberg, walmart, uber, aurora, confluent, visa, paypal, snapchat, salesforce, bytedance, cloudflare, adobe, nvidia, yandex, samsung, linkedin, citadel, shopify, intuit, servicenow, rubrik
*/
public class LRUCache {
public static void main(String[] args) {
LRUCacheUsingDoublyLinkedList cache = new LRUCacheUsingDoublyLinkedList(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
System.out.println( "cache.get(1): " + cache.get(2)); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
System.out.println( "cache.get(1): " + cache.get(1)); // returns -1 (not found)
System.out.println( "cache.get(3): " + cache.get(3)); // returns 3
System.out.println( "cache.get(4): " + cache.get(4)); // returns 4
}
/**
* see {@link DataStructures.HashMapExample} javaDoc
* accessOrder==true --> orderByAccess not by insertion
*/
static class LRUCacheUsingLinkedHashMapAccessOrderAsParent extends LinkedHashMap<Integer, Integer> {
int capacity;
public LRUCacheUsingLinkedHashMapAccessOrderAsParent(int capacity) {
super(capacity+1, 1f, true); // --> as capacity is not changing or use default super(capacity, 0.75f, true);
this.capacity = capacity;
}
@Override // it's automatically called after every put() in LinkedHashMap
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity; // Automatically remove LRU
}
public int get(int key) {
return getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
}
static class LRUCacheUsingLinkedHashMapAccessOrder {
Map<Integer, Integer> cache;
public LRUCacheUsingLinkedHashMapAccessOrder(int capacity) {
cache = new LinkedHashMap<>(capacity, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {return size() > capacity;}
};
}
public int get(int key) {return cache.getOrDefault(key, -1);}
public void put(int key, int value) {cache.put(key, value);}
}
/**
* It's just the internal implementation of LinkedHashMap with accessOrder instead of insertionOrder
*/
static class LRUCacheUsingDoublyLinkedList {
int capacity;
static class Node { int key; int val; Node prev; Node next; Node(){} Node(int key, int val) {this.key=key; this.val=val;}}
Node dummyHead = new Node(0,0), dummyTail = new Node(0,0);
Map<Integer, Node> map = new HashMap<>();
public LRUCacheUsingDoublyLinkedList(int capacity) {
this.capacity = capacity;
dummyHead.next = dummyTail;
dummyTail.prev = dummyHead;
}
public int get(int key) {
if (map.containsKey(key)) {
Node node = map.get(key);
updateCache(node);
return node.val;
}
return -1;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node node = map.get(key);
updateCache(node);
node.val = value;
} else {
Node node = new Node(key, value);
Node tail = dummyTail.prev;
tail.next = node;
node.prev = tail;
node.next = dummyTail;
dummyTail.prev = node;
map.put(key, node);
}
if (map.size() > capacity) {
Node lru = dummyHead.next; // actual head
dummyHead.next = lru.next;
lru.next.prev = dummyHead;
map.remove(lru.key);
}
}
private void updateCache(Node node) {
if (node == dummyTail.prev) return;
Node prevNode = node.prev;
Node nextNode = node.next;
prevNode.next = node.next;
nextNode.prev = node.prev;
Node tail = dummyTail.prev;
tail.next = node;
node.prev = tail;
node.next = dummyTail;
dummyTail.prev = node;
}
}
static class LRUCacheUsingDoublyLinkedList2 {
static class Node {int key, value; Node prev, next; Node(int k, int v) { key = k; value = v; }}
private final Map<Integer, Node> map = new HashMap<>();
private final int capacity;
private final Node dummyHead = new Node(0, 0);
private final Node dummyTail = new Node(0, 0);
public LRUCacheUsingDoublyLinkedList2(int capacity) {
this.capacity = capacity;
dummyHead.next = dummyTail;
dummyTail.prev = dummyHead;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node node = map.get(key);
remove(node);
insert(node);
return node.value;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
remove(node);
insert(node);
} else {
if (map.size() == capacity) {
Node lru = dummyHead.next; // actual head
remove(lru);
map.remove(lru.key);
}
Node newNode = new Node(key, value);
map.put(key, newNode);
insert(newNode);
}
}
private void remove(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void insert(Node node) {
Node tail = dummyTail.prev;
tail.next = node;
node.prev = tail;
node.next = dummyTail;
dummyTail.prev = node;
}
}
static class LRUCacheUsingLinkedHashMap {
Map<Integer, Integer> cache = new LinkedHashMap<>();
int capacity;
public LRUCacheUsingLinkedHashMap(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if (cache.containsKey(key)) {
int val = cache.get(key);
cache.remove(key);
cache.put(key, val);
return val;
}
return -1;
}
public void put(int key, int value) {
cache.remove(key);
cache.put(key, value);
if(cache.size()>capacity) {
int removeKey = cache.keySet().iterator().next();
cache.remove(removeKey);
}
}
}
/**
* Use (LinkedHashSet with HashMap) or (LinkedHashMap with insertionOrder)
* ---> and then remove from the middle and add to the end
*/
static class LRUCacheUsingLinkedHashSetAndHashMap {
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> set = new LinkedHashSet<>();
int size = 0;
public LRUCacheUsingLinkedHashSetAndHashMap(int capacity) {
size = capacity;
}
public int get(int key) {
if(set.contains(key)) {
set.remove(key);
set.add(key);
}
return map.getOrDefault(key, -1);
}
public void put(int key, int value) {
map.put(key, value);
set.remove(key);
set.add(key);
if(map.size() > size) {
int lru = set.iterator().next(); // set.stream().findFirst().orElse(null);
set.remove(lru);
map.remove(lru);
}
}
}
/**
* Remove from the middle and add to the end
* Brute force
*/
static class LRUCacheUsingHashMapAndArrayList {
private final int capcity;
private Map<Integer, Integer> map = new HashMap<>();
private List<Integer> lst = new ArrayList<>();
public LRUCacheUsingHashMapAndArrayList(int capacity) {
this.capcity = capacity;
}
// Working but TLE
public int get(int key) {
if (map.containsKey(key)) {
lst.remove(Integer.valueOf(key)); // --> remove from the middle
lst.add(key); // --> add to the end
}
return map.getOrDefault(key, -1);
}
// Working but TLE
public void put(int key, int value) {
if (capcity == map.size() && !map.containsKey(key)) {
map.remove(lst.get(0));
lst.remove(0);
}
if (map.containsKey(key)) { // or use this in else case with above if case
lst.remove(Integer.valueOf(key));
}
lst.add(key);
map.put(key, value);
System.out.println("map: " + map);
System.out.println("lst: " + lst);
}
}
}