Created
February 20, 2025 06:24
-
-
Save aroranubhav/ad9b8cb09089ab507c4ad826ebbdc834 to your computer and use it in GitHub Desktop.
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class LRUCache(private val capacity: Int) { | |
| inner class Node( | |
| val key: Int, | |
| val value: Int, | |
| var next: Node? = null, | |
| var prev: Node? = null | |
| ) | |
| private val cache = mutableMapOf<Int, Node>() | |
| private val left = Node(0, 0) | |
| private val right = Node(0, 0) | |
| init { | |
| left.next = right | |
| right.prev = left | |
| } | |
| fun get(key: Int): Int { | |
| return cache[key]?.let { node -> | |
| remove(node) | |
| insert(node) | |
| node.value | |
| } ?: -1 | |
| } | |
| fun put(key: Int, value: Int) { | |
| cache[key]?.let { node -> | |
| remove(node) | |
| cache.remove(key) | |
| } | |
| val node = Node(key, value) | |
| insert(node) | |
| cache[key] = node | |
| if (cache.size > capacity) { | |
| left.next?.let { lruNode -> | |
| remove(lruNode) | |
| cache.remove(lruNode.key) | |
| } | |
| } | |
| } | |
| private fun remove(node: Node) { | |
| val prev = node.prev | |
| val next = node.next | |
| prev?.next = next | |
| next?.prev = prev | |
| } | |
| private fun insert(node: Node) { | |
| val prev = right.prev | |
| val next = right | |
| prev?.next = node | |
| next.prev = node | |
| node.prev = prev | |
| node.next = next | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment