Time Based Key Value Store
Detailed guide and Python implementation for the 'Time Based Key Value Store' problem.
Problem Statement
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.
- set(key: str, value: str, timestamp: int) Stores the key key with the value value at the given time timestamp.
- get(key: str, timestamp: int) -> str 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 "".
- •1 <= key.length, value.length <= 100
- •key and value consist of lowercase English letters and digits
- •1 <= timestamp <= 10^7
- •All timestamps of set are strictly increasing for each key
- •At most 2 * 10^5 calls will be made to set and get
Examples
["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
[None, None, "bar", "bar", None, "bar2", "bar2"]
set("foo", "bar", 1): stores bar at time 1. get("foo", 1): returns "bar". get("foo", 3): returns "bar" (latest value at or before time 3). set("foo", "bar2", 4): stores bar2 at time 4. get("foo", 4): returns "bar2". get("foo", 5): returns "bar2".
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Datetime
Learn how to handle dates, times, timezones, and calculations in Python. Master formatting, parsing, and arithmetic using datetime and timedelta.
How to Sort a Dictionary by Value in Python
Learn how to sort a Python dictionary by its values. Discover sorting using sorted(), custom key lambdas, and building ordered dict structures.
Python DateTime Formatting
Learn how to parse and format dates and times in Python using datetime, strftime, and strptime.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.