Binary search · Medium
An audit API receives many historical lookups against the same revision export. Scanning the entire export for each lookup makes the endpoint too slow.
Build an in-memory revision index and answer each record lookup at its own cutoff time.
Input
Call
- Implement solve({revisions, queries}); do not mutate either array.
Revision export
- Each revision has an id, timestamp time, sequence tie-break and string value.
- Revisions may be unsorted. For one ID, (time, sequence) pairs are unique.
Lookups
- Each query selects one id at an inclusive cutoff time. Queries may be unsorted and repeated.
Output
Return value
- Return an array in query order; each element is the selected value or null.
- Select the latest eligible time for that ID, then the largest sequence at that time.
- A future revision must not hide an older eligible one. Empty string remains a valid result.
Constraints
- 0 <= revisions.length <= 100000; 0 <= queries.length <= 100000.
- Time, sequence and cutoff are integers in [0,1000000000]. IDs and values are ASCII strings of at most 40 characters.
Examples
Example 1
{
"queries": [
{
"id": "a",
"cutoff": 2
},
{
"id": "a",
"cutoff": 1
}
],
"revisions": [
{
"id": "a",
"time": 2,
"sequence": 0,
"value": "new"
},
{
"id": "a",
"time": 1,
"sequence": 0,
"value": "old"
}
]
}Returns
[
"new",
"old"
]Example 2
{
"queries": [
{
"id": "a",
"cutoff": 0
}
],
"revisions": []
}Returns
[
null
]Required complexity
O(n log n + q log(n + 1)) time and O(n + q) space