You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Design and implement a data structure for Least Frequently Used (LFU) cache.
18
+
It should support the following operations: get and put.
19
+
20
+
get(key) - Get the value (will always be positive) of the key
21
+
if the key exists in the cache, otherwise return -1.
22
+
23
+
put(key, value) - Set or insert the value if the key is not already present.
24
+
When the cache reaches its capacity, it should invalidate the least frequently used item
25
+
before inserting a new item. For the purpose of this problem,
26
+
when there is a tie (i.e., two or more keys that have the same frequency),
27
+
the least recently used key would be evicted.
28
+
29
+
Follow up:
30
+
Could you do both operations in O(1) time complexity?
31
+
32
+
Example:
33
+
34
+
LFUCache cache = new LFUCache( 2 ); // capacity
35
+
36
+
cache.put(1, 1);
37
+
cache.put(2, 2);
38
+
cache.get(1); // returns 1
39
+
cache.put(3, 3); // evicts key 2
40
+
cache.get(2); // returns -1 (not found)
41
+
cache.get(3); // returns 3.
42
+
cache.put(4, 4); // evicts key 1.
43
+
cache.get(1); // returns -1 (not found)
44
+
cache.get(3); // returns 3
45
+
cache.get(4); // returns 4
46
+
47
+
*/
48
+
49
+
50
+
/*
51
+
Goal:
52
+
get(key): value(+ int), -1
53
+
put(key, val).
54
+
if at cap, remove least frequent (smallest count); if count equal, remove old key
55
+
option1. pq, to store sort the order (frequency, recency). O(logn) for insertion. NOT OKAY
56
+
option2:
57
+
- hashmap to find value by key quickly,
58
+
- frequency map to track <frequency #, list of items>
59
+
- freqPosition map to track <key, item position in frequency list>
60
+
- int minFrequency to track the lowest frequency (to remove when reached capacity)
61
+
- constant capacity
62
+
63
+
Option2 gives O(1) get(); put() avg O(1)
64
+
65
+
Get:
66
+
Find key from map, retrieve existing frequency and find it on freqMap, move the item to a new frequency++ on freqMap, update freqPosition
67
+
68
+
Put:
69
+
If exist, simply update the value for the key, return.
70
+
If not exist:
71
+
- (optional)if over capacity: find freqMap[minFreq]'s least frequent item, remove item.key from map, remove item.key freqPosition map, remove the item from freqMap (first item in the list)
72
+
- it's new item with freq==1, add to hashmap, add to frequency map, and add the freq list position to freqPosition.
0 commit comments