|
| 1 | +2622\. Cache With Time Limit |
| 2 | + |
| 3 | +Medium |
| 4 | + |
| 5 | +Write a class that allows getting and setting key-value pairs, however a **time until expiration** is associated with each key. |
| 6 | + |
| 7 | +The class has three public methods: |
| 8 | + |
| 9 | +`set(key, value, duration)`: accepts an integer `key`, an integer `value`, and a `duration` in milliseconds. Once the `duration` has elapsed, the key should be inaccessible. The method should return `true` if the same un-expired key already exists and `false` otherwise. Both the value and duration should be overwritten if the key already exists. |
| 10 | + |
| 11 | +`get(key)`: if an un-expired key exists, it should return the associated value. Otherwise it should return `-1`. |
| 12 | + |
| 13 | +`count()`: returns the count of un-expired keys. |
| 14 | + |
| 15 | +**Example 1:** |
| 16 | + |
| 17 | +**Input:** ["TimeLimitedCache", "set", "get", "count", "get"] [[], [1, 42, 100], [1], [], [1]] [0, 0, 50, 50, 150] |
| 18 | + |
| 19 | +**Output:** [null, false, 42, 1, -1] |
| 20 | + |
| 21 | +**Explanation:** |
| 22 | + |
| 23 | +At t=0, the cache is constructed. |
| 24 | + |
| 25 | +At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned. |
| 26 | + |
| 27 | +At t=50, key=1 is requested and the value of 42 is returned. |
| 28 | + |
| 29 | +At t=50, count() is called and there is one active key in the cache. |
| 30 | + |
| 31 | +At t=100, key=1 expires. |
| 32 | + |
| 33 | +At t=150, get(1) is called but -1 is returned because the cache is empty. |
| 34 | + |
| 35 | +**Example 2:** |
| 36 | + |
| 37 | +**Input:** ["TimeLimitedCache", "set", "set", "get", "get", "get", "count"] [[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []] [0, 0, 40, 50, 120, 200, 250] |
| 38 | + |
| 39 | +**Output:** [null, false, true, 50, 50, -1] |
| 40 | + |
| 41 | +**Explanation:** |
| 42 | + |
| 43 | +At t=0, the cache is constructed. |
| 44 | + |
| 45 | +At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned. |
| 46 | + |
| 47 | +At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten. |
| 48 | + |
| 49 | +At t=50, get(1) is called which returned 50. At t=120, get(1) is called which returned 50. |
| 50 | + |
| 51 | +At t=140, key=1 expires. At t=200, get(1) is called but the cache is empty so -1 is returned. |
| 52 | + |
| 53 | +At t=250, count() returns 0 because the cache is empty. |
| 54 | + |
| 55 | +**Constraints:** |
| 56 | + |
| 57 | +* <code>0 <= key <= 10<sup>9</sup></code> |
| 58 | +* <code>0 <= value <= 10<sup>9</sup></code> |
| 59 | +* `0 <= duration <= 1000` |
| 60 | +* `total method calls will not exceed 100` |
0 commit comments