Apple Music needs a fast caching layer to store recently played songs and their metadata, enhancing user experience by minimizing load times while playing music.
Class LRUCache:
-
LRUCache(int capacity): Initializes the LRU cache with a positive size cap.
-
int get(int key): Returns the value of the key if the key exists, otherwise returns -1.
-
void put(int key, int value): Updates the value of the key if it exists, or adds the key-value pair if it doesn't. When the cache reached its capacity, it should invalidate the least recently used item before inserting the new item.
Example 1:Input:
cache = LRUCache(2), cache.put(1, 1), cache.put(2, 2), cache.get(1)Output:
1Explanation: Returns 1 and makes key 1 the most-recently used.
Example 2:Input:
cache.put(3, 3), cache.get(2)Output:
-1Explanation: Key 2 was already evicted due to reaching the capacity limit.
Constraints:-
1 <= capacity <= 3000-
0 <= key, value <= 10^4