50. Latest Event at or Before a Time
Difficulty: Medium · Topic: DSA for data engineers
Exchange rates are recorded at sorted times. Write as_of(times, values, queries): times is sorted ascending (it may contain repeats) and values[i] was recorded at times[i]. For each query time q, return the value of the latest record with time <= q; for equal times, the later record wins. If no record is that early, return None.
Return one answer per query, in query order. With 100,000 records and 100,000 queries, it must be O(log n) per query.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
as_of([10, 20, 30], [1.1, 1.2, 1.3], [5, 10, 25, 99])Expected: [None, 1.1, 1.2, 1.3]
Hints
Hint 1
bisect.bisect_right(times, q) is the number of records with time <= q.Hint 2
The answer is the record just before that position.Hint 3
bisect_right also lands after equal times, which picks the later record.Learn the concepts
- Sorting with key functions · 5 min read. Tuple keys, mixed directions, stability and data with None in it.
- Sliding windows, sweeps and binary search · 5 min read. O(n) windows, sort-then-sweep for intervals, and bisect for as-of lookups.
More Python problems
- Two Sum · Easy
- Valid Brackets · Easy
- First Non-Repeating Character · Easy
- Group Anagrams · Medium
- Longest Substring Without Repeats · Medium
- Top K Frequent with a Heap · Medium
- Merge K Sorted Linked Lists · Hard
- Task Order with Cycle Detection · Hard