Find the oldest index in a rotated array with duplicates
A fitness tracker stores heart-rate samples in a fixed-size circular buffer. Each sample has a timestamp, and timestamps never go down as samples are written. When the buffer is full, the writer wraps around and overwrites the oldest slot. Several samples can share a timestamp because the sensor writes bursts within the same millisecond.
When the app syncs, it receives the raw buffer: an array of timestamps that is a non-decreasing sequence, rotated by an unknown amount. To replay the samples in order, it needs to know where the oldest sample sits.
Implement findOldestEntry(timestamps). It returns the index where the original, non-decreasing order starts.
findOldestEntry(timestamps) // => index, or -1 for an empty buffer
timestamps is a non-decreasing array of numbers that may have been rotated: some prefix was moved to the end. For example, [3, 9, 9, 21, 40] rotated by 3 is [21, 40, 3, 9, 9].i where timestamps[i] < timestamps[i - 1]. Return that i.0.-1 for an empty array.findOldestEntry([40, 52, 67, 3, 9, 21]); // => 3
findOldestEntry([2, 3, 4, 5, 1]); // => 4
findOldestEntry([1, 2, 3, 4]); // => 0 (never wrapped)
findOldestEntry([3, 3, 1, 3]); // => 2
findOldestEntry([1, 1, 1, 2, 1]); // => 4
findOldestEntry([5, 5, 5]); // => 0 (all equal)
findOldestEntry([]); // => -1