Daily Algorithm - Time Based Key-Value Store

Ahyeon Lee이아현·2023년 7월 16일

DailyAlgorithm

목록 보기
4/6

Description

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's value at a certain timestamp.

Implement the TimeMap class:

  • TimeMap() Initializes the object of the data structure.
  • void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.
  • String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".

Example 1:

Input
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output
[null, null, "bar", "bar", null, "bar2", "bar2"]

Explanation
TimeMap timeMap = new TimeMap();
timeMap.set("foo", "bar", 1);  // store the key "foo" and value "bar" along with timestamp = 1.
timeMap.get("foo", 1);         // return "bar"
timeMap.get("foo", 3);         // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
timeMap.get("foo", 4);         // return "bar2"
timeMap.get("foo", 5);         // return "bar2"

Constraints:

  • 1 <= key.length, value.length <= 100
  • key and value consist of lowercase English letters and digits.
  • 1 <= timestamp <= 107
  • All the timestamps timestamp of set are strictly increasing.
  • At most 2 * 105 calls will be made to set and get.

Solution

  • set()으로 값을 넣을때 하나의 key에 오름차순으로 각기 다른 timestamp를 가진 value 값을 여러개 넣을 수 있다. 따라서 하나의 keytimestampvalue를 쌍으로 여러개 가진 HashMap<String, MutableList<Pair<Int, String>>>에 저장할 것이다.
  • get()으로 값을 가져올 땐 HashMap의 key의 리스트에서 timestamp와 가장 가까운 Pair의 second 값을 가져오면 된다.
  • timestamp 이하의 가장 가까운 값을 가져오면 되므로 이진 탐색을 이용해 key의 리스트에서 l과 r을 좁혀간다.
  • 가운데 값의 timestamp가 타겟 timestamp 보다 작거나 같으면 가운데 인덱스의 value를 result에 할당하면서 timestamp 이하의 값 중 가장 가까운 값을 찾는다.
class TimeMap() {
    
    val map: HashMap<String, MutableList<Pair<Int, String>>> = hashMapOf()

    fun set(key: String, value: String, timestamp: Int) {
        if (map[key] == null) {
            map[key] = mutableListOf<Pair<Int, String>>()
        }
        map[key]!!.add(Pair(timestamp, value))
    }

    fun get(key: String, timestamp: Int): String {
        var result = ""
        val pairList = map[key]
        
        pairList?.let { list ->
            var l = 0
            var r = list.lastIndex
            
            while (l <= r) {
                val m = (l + r) / 2
                if (list[m].first <= timestamp) {
                    result = list[m].second
                    l = m + 1
                } else {
                    r = m - 1
                }
            }
        }
        
        return result
    }

}
profile
원리를 알아야 내가 만드는 것을 알 수 있다

0개의 댓글