FastPrepLRU Cache

LRU Cache

JP Morgan Chase logoJP Morgan Chase● MediumFULLTIMEONSITE INTERVIEW

Problem statement

Build a least recently used (LRU) cache that holds at most capacity keys, then run the operations in operations in order.

  • "PUT key value" stores value under key. If the key is already stored, its value is replaced and nothing is evicted. If the key is new and the cache already holds capacity keys, first remove the least recently used key.
  • "GET key" returns the stored value, or -1 if the key is not in the cache.
  • A PUT and a GET that finds its key both make that key the most recently used. A GET that misses changes nothing.

Return the results of all GET operations, in order.

Aim for O(1) average time for each operation. The judge checks only the returned results, not the running time.

Function

runLRU(capacity: int, operations: String[]) → int[]

Examples

Example 1

capacity = 3operations = ["PUT 5 1","PUT 6 2","PUT 7 3","GET 5","PUT 8 4","GET 6","GET 7","GET 8","GET 5"]return = [1,-1,3,4,1]

The cache fills with keys 5, 6 and 7. GET 5 returns 1 and makes key 5 the most recent, so key 6 is now the least recently used and PUT 8 4 evicts it. The remaining gets return -1, 3, 4 and 1.

Example 2

capacity = 2operations = ["PUT 3 30","PUT 4 40","PUT 3 33","PUT 9 90","GET 4","GET 3","GET 9"]return = [-1,33,90]

PUT 3 33 replaces the value of key 3 and makes it the most recent, without evicting anything. When PUT 9 90 needs room, key 4 is the least recently used, so it is removed. The gets return -1, 33 and 90.

Example 3

capacity = 1operations = ["PUT 2 7","GET 3","GET 2","PUT 4 8","GET 2","GET 4"]return = [-1,7,-1,8]

GET 3 misses and returns -1 without changing anything. With capacity 1, PUT 4 8 evicts key 2, so the later GET 2 returns -1 and GET 4 returns 8.

Constraints

  • 1 <= capacity <= 3000
  • 1 <= operations.length <= 10^4
  • Each operation is "PUT key value" or "GET key", with single spaces and no leading zeros.
  • 0 <= key <= 10^4 and 0 <= value <= 10^5
  • At least one operation is a GET.

More JP Morgan Chase problems

See JP Morgan Chase hiring insights
Saved
public int[] runLRU(int capacity, String[] operations) {
    // Write your code here.
}
Checking account…