Earliest Entry in a Ring Log
Medium · Binary Search · about 20 min
A sensor writes timestamps into a ring buffer. The timestamps are all different and were written in increasing order, but the buffer wraps around, so the list you read starts somewhere in the middle: it is a sorted list that has been rotated (possibly by zero places).
Return the smallest timestamp in the list in O(log n) steps. The list always has at least one entry.
Example: ring_log_earliest([30, 40, 50, 10, 20]) → 10
Example: ring_log_earliest([10, 20, 30]) → 10 (not rotated)
Constraints: 1 to 100,000,000 entries; timestamps are integers and may be negative.
Hints
- Look at the middle value and the last value of the range. What does it mean if the middle one is bigger?
- If the middle is bigger than the last, the wrap point is to the right of the middle. If not, the right part is sorted and the smallest is at the middle or to its left.
- In the second case keep the middle in the range. Stop when the range has one index left.
Learn the pattern first: the Binary Search lesson.
More Binary Search problems
- Biggest Square of Tiles (Easy)
- Bookings at One Minute (Easy)
- Find a Book on a Rotated Shelf (Medium)
- Slowest Reading Pace (Medium)
- Fair Editing Shifts (Hard)
- K-th Cheapest Across Two Stores (Hard)