Your Dashboard
Interview Coaching
Learn
System Design
ML System Design
Code
Behavioral
Salary Negotiation
Interview Guides
Leetcode 981. Time Based Key-Value Store
Design a time-based key-value store that records multiple values per key with timestamps and returns the value whose timestamp is the largest <= the queried timestamp. With timestamps per key strictly increasing and up to 2e5 operations, the typical solution uses per-key ordered timestamp/value lists and binary search to find the floor timestamp efficiently.
Asked at:
OpenAI
Apple
Amazon
Meta
DESCRIPTION
Design a time-based key-value store that records multiple values per key with timestamps and returns the value whose timestamp is the largest <= the queried timestamp. With timestamps per key strictly increasing and up to 2e5 operations, the typical solution uses per-key ordered timestamp/value lists and binary search to find the floor timestamp efficiently.
Input:
Output:
Explanation: set('foo', 'bar1', 1) stores bar1 at time 1. set('foo', 'bar2', 4) stores bar2 at time 4. get('foo', 3) returns bar1 (largest timestamp <= 3 is 1). get('foo', 5) returns bar2 (largest timestamp <= 5 is 4)
Constraints:
- 1 <= key.length, value.length <= 100
- key and value consist of lowercase English letters and digits
- 1 <= timestamp <= 10^7
- All timestamps for set operations are strictly increasing per key
- At most 2 * 10^5 calls to set and get
Understanding the Problem
Let's understand what we're being asked to design. We need a time-based key-value store that can store multiple values for the same key, each with a different timestamp.
For example, if we do set('foo', 'bar1', timestamp=1) and later set('foo', 'bar2', timestamp=4), the key 'foo' now has two values associated with different times.
When we call get('foo', timestamp=3), we need to return the value whose timestamp is the largest timestamp less than or equal to 3. In this case, that's 'bar1' (timestamp 1), not 'bar2' (timestamp 4).
Important constraint: Timestamps for a given key are strictly increasing - we'll never set the same key with a timestamp less than or equal to a previous timestamp for that key.
Edge cases to consider: What if we get() a key that doesn't exist? What if we get() with a timestamp smaller than all stored timestamps for that key? What if there are up to 2 * 10^5 operations?
Building Intuition
Since timestamps for each key are strictly increasing, the values for each key form a sorted list by timestamp.
When we need to find the value with the largest timestamp <= queried_timestamp, we're essentially searching for a floor value in sorted data.
Searching in sorted data can be done very efficiently using binary search, achieving O(log n) time instead of O(n) linear scan.
With up to 2 * 10^5 operations, this efficiency difference becomes critical - the difference between 200,000 comparisons and just 18 comparisons per lookup!
Think of organizing historical stock prices. For each stock symbol (key), you maintain a chronological list of (timestamp, price) pairs.
When someone asks 'What was the price at 3:45 PM?', you need to find the most recent price at or before 3:45 PM. Since prices are recorded in chronological order, you can use binary search to quickly locate the right entry instead of scanning through all historical records.
Common Mistakes
Optimal Solution
Use a hashmap where each key maps to a list of (timestamp, value) pairs. Since timestamps are strictly increasing per key, each list remains sorted by timestamp. For set() operations, append the new (timestamp, value) pair to the key's list in O(1) time. For get() operations, perform binary search on the key's sorted timestamp list to find the largest timestamp <= queried_timestamp in O(log n) time, where n is the number of values stored for that key.
Initialize time-based key-value store
0 / 74
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(1) for set, O(log n) for get set() appends to a list in constant time. get() performs binary search on a sorted list of timestamps, which takes logarithmic time relative to the number of entries for that key
Space Complexity: O(n) We store all key-value-timestamp tuples in the hashmap, where n is the total number of set operations performed
What We've Learned
- HashMap + Sorted List hybrid structure: When you need to store multiple time-series values per key, combine a HashMap for O(1) key lookup with per-key sorted lists for temporal ordering - this dual-layer structure enables efficient access by both key and time dimension.
- Binary search for floor value retrieval: Use binary search (bisect_right - 1 in Python, upper_bound - 1 in C++) to find the largest timestamp ≤ query time in O(log n) - this "floor search" pattern is critical for range queries where you need the most recent valid entry.
- Monotonic timestamp guarantee optimization: When timestamps are strictly increasing per key, you can append to lists in O(1) without sorting - recognize this constraint in problem statements as it eliminates the need for insertion sort or post-insertion reordering.
- Empty result edge case: Always check if binary search returns a valid index before accessing - if the query timestamp is smaller than all stored timestamps, your search will return -1 or an invalid position, requiring an empty string return rather than array access.
- Time-series data pattern: This HashMap + Binary Search combination applies broadly to versioned data systems, stock price lookups, configuration history, and event logs - any scenario where you query "what was the state at time T?" benefits from this structure.
- Space-time tradeoff insight: Storing all historical values trades O(n) space for O(log n) query time - compared to keeping only latest values, this temporal indexing enables point-in-time queries essential for audit trails, debugging, and time-travel features in real systems.
Related Concepts and Problems to Practice
The Time Based Key-Value Store problem requires binary search to efficiently find the floor timestamp in ordered lists. This lesson provides foundational understanding of binary search patterns that are directly applicable to implementing the get operation in the time-based store.
medium
This problem involves finding elements closest to a target value in a sorted array, which is conceptually similar to finding the largest timestamp <= query timestamp. Both require understanding of floor/ceiling operations and efficient searching in ordered data structures.
medium
This problem combines hashmap storage with binary search on timestamps to find the latest non-overlapping job. It practices the same pattern of maintaining sorted timestamp data and using binary search to query based on time constraints, similar to the time-based key-value store.
Test Your Understanding
Why is hashmap the right data structure for this problem?
hashmap provides the optimal access pattern
It's the only data structure that works
It's the easiest to implement
It uses the least memory
Select an answer to see the explanation
Question Timeline
See when this question was last asked and where, including any notes left by other candidates.
Mid October, 2025
OpenAI
Senior
Early August, 2025
Meta
Staff
Mid June, 2025
OpenAI
Staff
Comments
Hello Interview Premium
Your account is free and you can post anonymously if you choose.