MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / LRUCache

Class LRUCache

kotlin/Linked Lists/LRUCache.kt:6–66  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4}
5
6class LRUCache {
7
8 private val capacity: Int
9 private val hashmap: MutableMap<Int, DoublyLinkedListNode>
10 private val head: DoublyLinkedListNode
11 private val tail: DoublyLinkedListNode
12
13 constructor(capacity: Int) {
14 this.capacity = capacity
15 // A hash map that maps keys to nodes.
16 this.hashmap = mutableMapOf()
17 // Initialize the head and tail dummy nodes and connect them to
18 // each other to establish a basic two-node doubly linked list.
19 this.head = DoublyLinkedListNode(-1, -1)
20 this.tail = DoublyLinkedListNode(-1, -1)
21 this.head.next = this.tail
22 this.tail.prev = this.head
23 }
24
25 fun get(key: Int): Int {
26 if (key !in hashmap) {
27 return -1
28 }
29 // To make this key the most recently used, remove its node and
30 // re-add it to the tail of the linked list.
31 val node = hashmap[key]!!
32 removeNode(node)
33 addToTail(node)
34 return node.value
35 }
36
37 fun put(key: Int, value: Int) {
38 // If a node with this key already exists, remove it from the
39 // linked list.
40 if (key in hashmap) {
41 removeNode(hashmap[key]!!)
42 }
43 val node = DoublyLinkedListNode(key, value)
44 hashmap[key] = node
45 // Remove the least recently used node from the cache if adding
46 // this new node will result in an overflow.
47 if (hashmap.size > capacity) {
48 hashmap.remove(head.next!!.key)
49 removeNode(head.next!!)
50 }
51 addToTail(node)
52 }
53
54 private fun addToTail(node: DoublyLinkedListNode) {
55 val prevNode = tail.prev
56 node.prev = prevNode
57 node.next = tail
58 prevNode!!.next = node
59 tail.prev = node
60 }
61
62 private fun removeNode(node: DoublyLinkedListNode) {
63 node.prev!!.next = node.next

Callers

nothing calls this directly

Calls 1

Tested by

no test coverage detected