Ad platform~10 min2s · 256 MBtarget O(n) time, O(1) spacesorting
An ad server writes one line to a batch file for each ad impression. Each line carries the time of the impression in milliseconds. A batch is valid only when its times never go back.
A downstream job reads the batch and trusts that order. Before it starts, you check the batch. The job wants to know where the first mistake is.
You get the times in file order. Find the first entry that is earlier than an entry before it.
Write first_out_of_order(times).
times[i] is the time of the impression on line i, counting from 0.i such that some earlier line has a later time than times[i].Input: times = [2, 4, 4, 7, 6, 9]
Output: 4Compare each line with the line before it.
| Line | Time | Time before | Goes back? |
|---|---|---|---|
| 1 | 4 | 2 | no |
| 2 | 4 | 4 | no |
| 3 | 7 | 4 | no |
| 4 | 6 | 7 | yes |
Line 4 is the first that goes back, so the answer is 4. Five comparisons would be needed to clear the whole list, and the walk stops after four.
Input: times = [100, 105, 105, 130]
Output: -1No time is smaller than the one before it. Equal times are fine.
Input: times = [10, 20, 15, 30]
Output: 2Line 2 has time 15, which is earlier than 20 on line 1.
0 ≤ times.length ≤ 100,000 (impression lines)0 ≤ times[i] ≤ 1,000,000,000 (milliseconds)Comparing every line with every earlier line costs about n × n / 2 steps, which is 5 × 10^9 at n = 100,000. Comparing each line with its neighbour costs n − 1 steps.