Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. /*
  2. Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put.
  3.  
  4. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
  5. put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.
  6.  
  7. Follow up:
  8. Could you do both operations in O(1) time complexity?
  9. */
  10. // LinkedList
  11. class LFUCache {
  12. constructor (capacity) {
  13. // Caches need some way track recently accessed
  14. // use object to keep track of frequency (cache)
  15. // use object for storage (storage)
  16. // variable to store capacity
  17. }
  18.  
  19. put (key, value) {
  20. // puts values into storage object
  21. // push key into cache
  22. // if cache size > capacity
  23. // remove least frequently used item
  24. }
  25.  
  26. get (key) {
  27. // if key exists in storage
  28. // add
  29. }
  30.  
  31. }
  32.  
  33. var cache = new LFUCache( 2 /* capacity */ );
  34.  
  35. console.log(cache);
  36. cache.put(1, 1);
  37. cache.put(2, 2);
  38. cache.get(1); // returns 1
  39. cache.put(3, 3); // evicts key 2
  40. cache.get(2); // returns -1 (not found)
  41. cache.get(3); // returns 3.
  42. cache.put(4, 4); // evicts key 1.
  43. cache.get(1); // returns -1 (not found)
  44. cache.get(3); // returns 3
  45. cache.get(4); // returns 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement