FastPrepLRU Cache

LRU Cache

Zillow logoZillow● MediumFULLTIMEINTERNPHONE SCREENONSITE INTERVIEW

Updated

Problem statement

Build a least recently used (LRU) cache that holds at most capacity keys, each with an integer value. The cache starts empty.

You get three arrays of the same length: operations, keys and values. Run the operations from left to right. At index i, operations[i] is one of these:

  • "put": store values[i] under the key keys[i]. If the key is already in the cache, replace its value. If the key is new and the cache already holds capacity keys, first remove the least recently used key and its value. Either way, keys[i] becomes the most recently used key.
  • "get": if keys[i] is in the cache, add its value to the result and make it the most recently used key. Otherwise, add -1 to the result and change nothing.

Return the results of all "get" operations, in the order they ran.

Each "put" and "get" should take O(1) time on average.

Function

runLruCache(capacity: int, operations: String[], keys: int[], values: int[]) → int[]

Examples

Example 1

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

The cache holds keys 1 and 2 when key 1 is read, so key 1 becomes the most recently used and key 2 the least. Storing key 3 then removes key 2. The lookups return -1 for key 2, 30 for key 3 and 10 for key 1.

Example 2

capacity = 2operations = ["put","put","put","put","get","get","get"]keys = [1,2,1,3,1,2,3]values = [10,20,15,30,0,0,0]return = [15,-1,30]

The third operation replaces the value of key 1 with 15. That does not remove anything, because key 1 is already in the cache, but it makes key 1 the most recently used. So storing key 3 removes key 2, and the lookups return 15, -1 and 30.

Example 3

capacity = 1operations = ["get","put","get","put","get","get"]keys = [4,4,4,6,4,6]values = [0,0,0,1,0,0]return = [-1,0,-1,1]

The cache starts empty, so the first lookup returns -1. Key 4 is then stored with the value 0, which is a real value, so the next lookup returns 0. The cache holds one key, so storing key 6 removes key 4, and the last two lookups return -1 and 1.

Constraints

  • 1 <= capacity <= 3000
  • 1 <= operations.length <= 10000
  • keys.length == operations.length
  • values.length == operations.length
  • Each operations[i] is "put" or "get".
  • 0 <= keys[i] <= 10000
  • 0 <= values[i] <= 100000
  • When operations[i] is "get", values[i] is 0 and is not used.

More Zillow Phone Screen questions

Similar questions at other companies

All Zillow interview questionsSee Zillow hiring insights
Saved
class Solution {
    public int[] runLruCache(int capacity, String[] operations, int[] keys, int[] values) {
        // Write your code here.
    }
}
Checking account…