java.lang.Object
g0901_1000.s0981_time_based_key_value_store.TimeMap

public class TimeMap extends Object
981 - Time Based Key-Value Store.<p>Medium</p> <p>Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key&rsquo;s value at a certain timestamp.</p> <p>Implement the <code>TimeMap</code> class:</p> <ul> <li><code>TimeMap()</code> Initializes the object of the data structure.</li> <li><code>void set(String key, String value, int timestamp)</code> Stores the key <code>key</code> with the value <code>value</code> at the given time <code>timestamp</code>.</li> <li><code>String get(String key, int timestamp)</code> Returns a value such that <code>set</code> was called previously, with <code>timestamp_prev <= timestamp</code>. If there are multiple such values, it returns the value associated with the largest <code>timestamp_prev</code>. If there are no values, it returns <code>&quot;&quot;</code>.</li> </ul> <p><strong>Example 1:</strong></p> <p><strong>Input</strong></p> <p>[&ldquo;TimeMap&rdquo;, &ldquo;set&rdquo;, &ldquo;get&rdquo;, &ldquo;get&rdquo;, &ldquo;set&rdquo;, &ldquo;get&rdquo;, &ldquo;get&rdquo;]</p> <p>[ [], [&ldquo;foo&rdquo;, &ldquo;bar&rdquo;, 1], [&ldquo;foo&rdquo;, 1], [&ldquo;foo&rdquo;, 3], [&ldquo;foo&rdquo;, &ldquo;bar2&rdquo;, 4], [&ldquo;foo&rdquo;, 4], [&ldquo;foo&rdquo;, 5]]</p> <p><strong>Output:</strong> [null, null, &ldquo;bar&rdquo;, &ldquo;bar&rdquo;, null, &ldquo;bar2&rdquo;, &ldquo;bar2&rdquo;]</p> <p><strong>Explanation:</strong></p> <pre><code> TimeMap timeMap = new TimeMap(); timeMap.set(&quot;foo&quot;, &quot;bar&quot;, 1); // store the key &quot;foo&quot; and value &quot;bar&quot; along with timestamp = 1. timeMap.get(&quot;foo&quot;, 1); // return &quot;bar&quot; timeMap.get(&quot;foo&quot;, 3); // return &quot;bar&quot;, since there is no value corresponding to foo at timestamp 3 // and timestamp 2, then the only value is at timestamp 1 is &quot;bar&quot;. timeMap.set(&quot;foo&quot;, &quot;bar2&quot;, 4); // store the key &quot;foo&quot; and value &quot;bar2&quot; along with timestamp = 4. timeMap.get(&quot;foo&quot;, 4); // return &quot;bar2&quot; timeMap.get(&quot;foo&quot;, 5); // return &quot;bar2&quot; </code></pre> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= key.length, value.length <= 100</code></li> <li><code>key</code> and <code>value</code> consist of lowercase English letters and digits.</li> <li><code>1 <= timestamp <= 10<sup>7</sup></code></li> <li>All the timestamps <code>timestamp</code> of <code>set</code> are strictly increasing.</li> <li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>set</code> and <code>get</code>.</li> </ul>
  • Constructor Details

    • TimeMap

      public TimeMap()
  • Method Details

    • set

      public void set(String key, String value, int timestamp)
    • get

      public String get(String key, int timestamp)