Skip to content

Commit 0c6e04f

Browse files
committed
time_based_key_value_store_981: solved
1 parent 341ad88 commit 0c6e04f

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 981. Time Based Key-Value Store
2+
3+
https://leetcode.com/problems/time-based-key-value-store/description/
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package time_based_key_value_store_981
2+
3+
import "sort"
4+
5+
type entry struct {
6+
value string
7+
timestamp int
8+
}
9+
10+
type TimeMap struct {
11+
m map[string][]*entry
12+
}
13+
14+
func Constructor() TimeMap {
15+
return TimeMap{
16+
m: make(map[string][]*entry),
17+
}
18+
}
19+
20+
func (m *TimeMap) Set(key string, value string, timestamp int) {
21+
entries, ok := m.m[key]
22+
if !ok {
23+
entries = make([]*entry, 0)
24+
}
25+
26+
// perform a binary search for the sorted insertion point (timestamp asc)
27+
index := sort.Search(len(entries), func(i int) bool {
28+
return entries[i].timestamp > timestamp
29+
})
30+
31+
// insert the new entry at the sorted insertion point
32+
newEntry := &entry{value: value, timestamp: timestamp}
33+
if index == len(entries) {
34+
entries = append(entries, newEntry)
35+
} else {
36+
// perform a copy-shift insert
37+
entries = append(entries, nil) // make space
38+
copy(entries[index+1:], entries[index:])
39+
entries[index] = newEntry
40+
}
41+
42+
m.m[key] = entries
43+
}
44+
45+
func (m *TimeMap) Get(key string, timestamp int) string {
46+
entries, ok := m.m[key]
47+
if !ok {
48+
return ""
49+
}
50+
51+
// Find the first entry where the timestamp is greater. This means
52+
// the one right behind it is our entry to return.
53+
index := sort.Search(len(entries), func(i int) bool {
54+
return entries[i].timestamp > timestamp
55+
})
56+
if index == 0 {
57+
return ""
58+
}
59+
60+
return entries[index-1].value
61+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package time_based_key_value_store_981
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestKV(t *testing.T) {
10+
kv := Constructor()
11+
kv.Set("foo", "bar", 1)
12+
kv.Set("foo", "baz", 4)
13+
assert.Equal(t, "", kv.Get("foo", 0))
14+
assert.Equal(t, "bar", kv.Get("foo", 3))
15+
assert.Equal(t, "bar", kv.Get("foo", 2))
16+
assert.Equal(t, "baz", kv.Get("foo", 4))
17+
assert.Equal(t, "baz", kv.Get("foo", 6))
18+
}

0 commit comments

Comments
 (0)