FastPrepLRU Cache Operations

LRU Cache Operations

Hevo Data logoHevo Data● MediumNEW GRADONSITE INTERVIEW

Problem statement

Process a finite sequence of calls to an initially empty least-recently-used (LRU) cache that holds at most capacity key-value pairs.

  • [1, key, value] is a put call. Insert the pair, or replace its value if the key already exists. This key becomes the most recently used. If inserting a new key would exceed capacity, evict the least recently used key.
  • [0, key, 0] is a get call. Return the stored value and make that key the most recently used, or return -1 if the key is absent. A miss does not change the cache order.

Return one result for each get call, in call order. Put calls produce no result. Each invocation starts with an empty cache.

Function

lruCacheOperations(capacity: int, operations: int[][]) → int[]

Examples

Example 1

capacity = 2operations = [[1,1,10],[1,2,20],[0,1,0],[1,3,30],[0,2,0],[0,3,0]]return = [10,-1,30]

Getting key 1 makes key 2 the least recently used. Inserting key 3 evicts key 2. The three gets return 10, -1, and 30.

Example 2

capacity = 1operations = [[1,5,7],[1,5,9],[0,5,0],[1,6,0],[0,5,0],[0,6,0]]return = [9,-1,0]

Updating key 5 changes its value to 9 without adding another entry. Inserting key 6 then evicts it. A stored value of 0 is a hit.

Constraints

  • 1 <= capacity <= 10000.
  • 0 <= operations.length <= 100000.
  • Each operation has exactly 3 integers.
  • 0 <= operations[i][j] <= 10^9.
  • The first integer is 0 for get or 1 for put; the third integer of a get is 0.

More Hevo Data problems

See Hevo Data hiring insights
Saved
public int[] lruCacheOperations(int capacity, int[][] operations) {
    // Write your code here
}
Checking account…