Menu
CoddyTech

LRU Cache

Build a cache that holds at most capacity keys. get key returns the key's value, or -1 if it is not cached. put key value stores the value, replacing any older one; if the key is new and the cache is full, it first evicts the least recently used key. A get that finds its key, and every put, counts as a use.

Operation i is ops[i] ("get" or "put") on key keys[i], with value values[i] (0 for a get). Run them in order on an empty cache and return one string each: "null" for a put, the value or "-1" for a get.

Function

lruCacheOps(capacity: integer, ops: string-array, keys: integer-array, values: integer-array) → string-array
capacityinteger
the most keys the cache can hold at once
opsstring-array
the operations, in the order they run
keysinteger-array
the key each operation works on
valuesinteger-array
the value for each put, 0 for each get
Returnsstring-array
one answer per operation, as text

Constraints

  • 1 ≤ capacity ≤ 3000
  • 1 ≤ ops.length ≤ 3000
  • keys.length == values.length == ops.length
  • Every ops[i] is get or put.
  • 0 ≤ keys[i] ≤ 109
  • 0 ≤ values[i] ≤ 109 for a put, and values[i] == 0 for a get.

Examples

Input
capacity = 2ops = ["put", "put", "get", "put", "get", "get"]keys = [1, 2, 1, 3, 2, 3]values = [10, 20, 0, 30, 0, 0]
Output
["null", "null", "10", "null", "-1", "30"]
Explanation
The get makes key 1 the most recently used, so put 3 evicts key 2: get 2 returns "-1" and get 3 returns "30".
challenge icon

Follow-up

How would you change the cache to evict the least frequently used key instead, breaking ties by the least recent use, still in O(1) per operation?

Reset code
def lruCacheOps(capacity, ops, keys, values):
    # Write code here

Test #1

Test #2

Test #3

Arguments

capacity = 2
ops = ["put", "put", "get", "put", "get", "get"]
keys = [1, 2, 1, 3, 2, 3]
values = [10, 20, 0, 30, 0, 0]

Expected Output

["null", "null", "10", "null", "-1", "30"]