Dodomeki
Sign in

137. Recency Cache with a Capacity Limit

Medium

Implement an LRU cache, which discards the least recently used item when it needs to make room. The cache capacity is capacidade; its operations are given in operacoes, with the corresponding arguments in valores.

Each entry in operacoes is guardar or ler. For guardar, the corresponding entry in valores contains [chave, valor]; for ler, it contains [chave]. Keys are strings and values are non-negative integers. Storing an existing key replaces its value.

Both storing and reading an existing key count as use and make that key the most recently used. Reading a missing key does not change the usage order. When storing a new item in a full cache, remove the least recently used item before inserting the new one.

Return an array with one result per operation, in the same order: use null for guardar and the retrieved value for ler. If the key does not exist, return -1.

Example 1
Input: capacidade = 2, operacoes = ["guardar", "guardar", "ler", "guardar", "ler", "ler"], valores = [["a", 1], ["b", 2], ["a"], ["c", 3], ["b"], ["c"]]
Output: [null, null, 1, null, -1, 3]
Explanation: Reading "a" makes it the most recent; when "c" is stored, the cache removes "b", which is now the least recent.
Example 2
Input: capacidade = 1, operacoes = ["guardar", "guardar", "ler", "ler"], valores = [["x", 4], ["x", 7], ["x"], ["y"]]
Output: [null, null, 7, -1]
Explanation: Storing "x" again updates its value; reading "y" does not find the key.
Constraints
  • 1 <= capacidade <= 10^5
  • 0 <= operacoes.length <= 2 * 10^5
  • operacoes.length == valores.length
  • operacoes[i] is "guardar" or "ler"
  • If operacoes[i] == "guardar", valores[i] contains exactly 2 elements
  • If operacoes[i] == "ler", valores[i] contains exactly 1 element
  • 1 <= chave.length <= 100
  • 0 <= valor <= 10^9
DesignHash mapLinked list
Caso 1
capacidade =
2
operacoes =
["guardar","guardar","ler","guardar","ler","ler"]
valores =
[["a",1],["b",2],["a"],["c",3],["b"],["c"]]
Expected =
[null,null,1,null,-1,3]
Caso 2
capacidade =
1
operacoes =
["guardar","guardar","ler","ler"]
valores =
[["x",4],["x",7],["x"],["y"]]
Expected =
[null,null,7,-1]

Run checks these 2 cases. Submit runs all 11, including hidden ones.