-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0981_time_based_key_value_store.html
More file actions
465 lines (403 loc) · 16.9 KB
/
Copy path0981_time_based_key_value_store.html
File metadata and controls
465 lines (403 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>981 - Time Based Key-Value Store</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#981</span> Time Based Key-Value Store</h1>
<p>
Design a time-based key-value data structure that can store multiple values
for the same key at different timestamps and retrieve the value at a certain timestamp.
Use binary search to find the largest timestamp ≤ given timestamp.
</p>
<div class="problem-meta">
<span class="meta-tag">📝 Algorithm</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0981_time_based_key_value_store/0981_time_based_key_value_store.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn" class="btn btn-success">Step Through Operations</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
</div>
<div class="status" id="status">Step through set() and get() operations</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from collections import defaultdict
import bisect
from typing import Dict, List, Tuple
"""
LeetCode Time Based Key Value Store
Problem from LeetCode: https://leetcode.com/problems/time-based-key-value-store/
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 <= 10^7
All the timestamps timestamp of set are strictly increasing.
At most 2 * 10^5 calls will be made to set and get.
"""
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.store = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) ->None:
"""
Store the key-value pair in the data structure.
Args:
key: The key to store
value: The value to store
timestamp: The timestamp for this key-value pair
"""
self.store[key].append((timestamp, value))
def get(self, key: str, timestamp: int) ->str:
"""
Return the value associated with the key at the timestamp.
Args:
key: The key to retrieve
timestamp: The timestamp to search for
Returns:
str: The value at the timestamp, or "" if not found
"""
if key not in self.store:
return ''
values = self.store[key]
idx = bisect.bisect_right(values, (timestamp, chr(127)))
if idx == 0:
return ''
return values[idx - 1][1]
class TimeMap_manual_binary_search:
def __init__(self):
"""
Initialize the TimeMap.
"""
self.store = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) ->None:
"""
Store the key-value pair.
"""
self.store[key].append((timestamp, value))
def get(self, key: str, timestamp: int) ->str:
"""
Get the value at or before the given timestamp.
"""
if key not in self.store:
return ''
values = self.store[key]
left, right = 0, len(values) - 1
while left <= right:
mid = (left + right) // 2
if values[mid][0] <= timestamp:
left = mid + 1
else:
right = mid - 1
if right >= 0:
return values[right][1]
else:
return ''
if __name__ == '__main__':
# Example usage based on LeetCode sample
timeMap = TimeMap()
timeMap.set("foo", "bar", 1)
print(timeMap.get("foo", 1)) # Output: "bar"
print(timeMap.get("foo", 3)) # Output: "bar"
timeMap.set("foo", "bar2", 4)
print(timeMap.get("foo", 4)) # Output: "bar2"
print(timeMap.get("foo", 5)) # Output: "bar2"
# Testing alternative implementation
print("\nTesting manual binary search implementation:")
timeMap2 = TimeMap_manual_binary_search()
timeMap2.set("foo", "bar", 1)
print(timeMap2.get("foo", 1)) # Output: "bar"
print(timeMap2.get("foo", 3)) # Output: "bar"
timeMap2.set("foo", "bar2", 4)
print(timeMap2.get("foo", 4)) # Output: "bar2"
print(timeMap2.get("foo", 5)) # Output: "bar2"
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// Operations to demonstrate
const operations = [
{ op: "set", key: "foo", value: "bar", timestamp: 1 },
{ op: "get", key: "foo", timestamp: 1 },
{ op: "get", key: "foo", timestamp: 3 },
{ op: "set", key: "foo", value: "bar2", timestamp: 4 },
{ op: "get", key: "foo", timestamp: 4 },
{ op: "get", key: "foo", timestamp: 5 },
{ op: "get", key: "foo", timestamp: 2 }
];
let store = {};
let currentOp = 0;
let binarySearchState = null;
let result = null;
function reset() {
store = {};
currentOp = 0;
binarySearchState = null;
result = null;
document.getElementById("status").textContent = "Step through set() and get() operations";
render();
}
function render() {
svg.selectAll("*").remove();
// Title
svg.append("text")
.attr("x", 30)
.attr("y", 35)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Time-Based Key-Value Store");
// Operations list
svg.append("text")
.attr("x", 30)
.attr("y", 70)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#64748b")
.text("Operations:");
operations.forEach((op, idx) => {
const y = 95 + idx * 25;
const isCurrent = idx === currentOp;
const isPast = idx < currentOp;
let text;
if (op.op === "set") {
text = `set("${op.key}", "${op.value}", ${op.timestamp})`;
} else {
text = `get("${op.key}", ${op.timestamp})`;
}
svg.append("text")
.attr("x", 40)
.attr("y", y)
.attr("font-size", "12px")
.attr("font-weight", isCurrent ? "bold" : "normal")
.attr("fill", isCurrent ? "#f59e0b" : isPast ? "#10b981" : "#94a3b8")
.text(`${idx + 1}. ${text}`);
if (isCurrent) {
svg.append("text")
.attr("x", 30)
.attr("y", y)
.attr("font-size", "12px")
.attr("fill", "#f59e0b")
.text("▶");
}
});
// Store visualization
const storeX = 350;
svg.append("text")
.attr("x", storeX)
.attr("y", 70)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Store: { key → [(timestamp, value), ...] }");
if (Object.keys(store).length === 0) {
svg.append("text")
.attr("x", storeX)
.attr("y", 100)
.attr("font-size", "13px")
.attr("fill", "#94a3b8")
.text("(empty)");
} else {
let yOffset = 100;
for (const [key, values] of Object.entries(store)) {
svg.append("text")
.attr("x", storeX)
.attr("y", yOffset)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#6366f1")
.text(`"${key}":`);
values.forEach((v, i) => {
const x = storeX + 70 + i * 110;
const isSearching = binarySearchState &&
binarySearchState.left <= i && i <= binarySearchState.right;
const isMid = binarySearchState && i === binarySearchState.mid;
svg.append("rect")
.attr("x", x)
.attr("y", yOffset - 18)
.attr("width", 100)
.attr("height", 30)
.attr("rx", 6)
.attr("fill", isMid ? "#fef3c7" : isSearching ? "#dbeafe" : "#f8fafc")
.attr("stroke", isMid ? "#f59e0b" : isSearching ? "#3b82f6" : "#94a3b8")
.attr("stroke-width", isMid ? 3 : 1);
svg.append("text")
.attr("x", x + 50)
.attr("y", yOffset)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#1e293b")
.text(`(${v[0]}, "${v[1]}")`);
});
yOffset += 50;
}
}
// Binary search visualization
if (binarySearchState) {
const bsY = 280;
svg.append("rect")
.attr("x", storeX)
.attr("y", bsY)
.attr("width", 400)
.attr("height", 80)
.attr("rx", 10)
.attr("fill", "#eff6ff")
.attr("stroke", "#3b82f6");
svg.append("text")
.attr("x", storeX + 10)
.attr("y", bsY + 25)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Binary Search State:");
svg.append("text")
.attr("x", storeX + 10)
.attr("y", bsY + 50)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(`left=${binarySearchState.left}, right=${binarySearchState.right}, mid=${binarySearchState.mid}`);
svg.append("text")
.attr("x", storeX + 10)
.attr("y", bsY + 70)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(`Looking for timestamp ≤ ${binarySearchState.target}`);
}
// Result
if (result !== null) {
const resultY = 400;
svg.append("rect")
.attr("x", storeX)
.attr("y", resultY)
.attr("width", 350)
.attr("height", 50)
.attr("rx", 10)
.attr("fill", "#d1fae5")
.attr("stroke", "#10b981")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", storeX + 175)
.attr("y", resultY + 32)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text(`Result: "${result}"`);
}
// Algorithm explanation
const algoY = 480;
svg.append("text")
.attr("x", 30)
.attr("y", algoY)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Key insight: Timestamps are always increasing → binary search for largest timestamp ≤ target");
}
function step() {
if (currentOp >= operations.length) {
document.getElementById("status").textContent = "All operations complete!";
return;
}
const op = operations[currentOp];
result = null;
binarySearchState = null;
if (op.op === "set") {
if (!store[op.key]) {
store[op.key] = [];
}
store[op.key].push([op.timestamp, op.value]);
document.getElementById("status").textContent =
`set("${op.key}", "${op.value}", ${op.timestamp}) - Added to store`;
} else {
// get operation with binary search
if (!store[op.key]) {
result = "";
document.getElementById("status").textContent =
`get("${op.key}", ${op.timestamp}) → "" (key not found)`;
} else {
const values = store[op.key];
let left = 0, right = values.length - 1;
result = "";
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (values[mid][0] <= op.timestamp) {
result = values[mid][1];
left = mid + 1;
} else {
right = mid - 1;
}
}
binarySearchState = {
left: 0,
right: values.length - 1,
mid: Math.floor((values.length - 1) / 2),
target: op.timestamp
};
document.getElementById("status").textContent =
`get("${op.key}", ${op.timestamp}) → "${result}" (binary search for timestamp ≤ ${op.timestamp})`;
}
}
currentOp++;
render();
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>