| Topic | Difficulty | Companies |
|---|---|---|
| Stack and Queue | HARD | Amazon Microsoft Adobe Google |
Design and implement a data structure for Least Recently Used(LRU) cache.
Problem Note:
get() and put()get(key): finds and returns the value if the key exists in the cacheget(key) returns -1put(key, value): inserts new key if it is not present in the cache. If the cache is filled to capacity, it must remove the least recently used entryO(1) time complexityget() and put()
Example
cache = LRUCache(3)
cache.put(1,1)
cache.put(2,2)
cache.put(1,3)
cache.get(1) ---> returns 3
cache.put(3,4)
cache.put(4,3) // removes key 2
cache.get(2) ---> returns -1
Input Format:
N and C, the total number of queries and the cache size.N lines has a query of either type 1(put) or type 2(get).1 k v, where k is key and v is value2 k, where k is key whose value is to be fetched.For example, the input for the above example will be:
7 3
1 1 1
1 2 2
1 1 3
2 1
1 3 4
1 4 3
2 2