Monitoring~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-977opposite-ends · two-pointers · merge-sorted
A monitoring system measures each server's clock drift in milliseconds: how far its clock is from the reference time. A negative drift means the clock is behind, and a positive drift means it is ahead. Each fleet report lists the drifts sorted from the most negative to the most positive.
The alerting model scores a drift by its size, not its direction, so it works with squared drifts. A clock 3 ms behind and a clock 3 ms ahead get the same score, 9. For every report, the model needs the squared drifts in order, from the smallest to the largest.
Write squared_drifts(drifts).
drifts[i] is the clock drift of server i in milliseconds. It may be negative, zero or positive.drifts is sorted in non-decreasing order, and it is never empty.Input: drifts = [-9, -4, -1, 0, 3, 5]
Output: [0, 1, 9, 16, 25, 81]| write | left | right | drifts[left] | drifts[right] | Squares at the ends | Written | result after the step |
|---|---|---|---|---|---|---|---|
| 5 | 0 | 5 | -9 | 5 | 81 and 25 | 81, from the left | _, _, _, _, _, 81 |
| 4 | 1 | 5 | -4 | 5 | 16 and 25 | 25, from the right | _, _, _, _, 25, 81 |
| 3 | 1 | 4 | -4 | 3 | 16 and 9 | 16, from the left | _, _, _, 16, 25, 81 |
| 2 | 2 | 4 | -1 | 3 | 1 and 9 | 9, from the right | _, _, 9, 16, 25, 81 |
| 1 | 2 | 3 | -1 | 0 | 1 and 0 | 1, from the left | _, 1, 9, 16, 25, 81 |
| 0 | 3 | 3 | 0 | 0 | 0 and 0 | 0, the last drift | 0, 1, 9, 16, 25, 81 |
The largest square, 81, comes from the most negative drift. The smallest, 0, sits in the middle of the list.
Input: drifts = [-3, -3, 0, 3]
Output: [0, 9, 9, 9]The drifts -3 and 3 square to the same number, so 9 appears three times.
Input: drifts = [-6, -4, -1]
Output: [1, 16, 36]Every server is behind, so the squares come out in the reverse order of the drifts.
1 ≤ drifts.length ≤ 10^5-10^4 ≤ drifts[i] ≤ 10^4 (10 seconds either way), and drifts[i] ≤ drifts[i + 1] for every iSquaring every drift and sorting the squares is O(n log n): about 1.7 × 10^6 comparisons at n = 10^5. That fits the limit with room to spare. A sort that compares neighbours, such as insertion sort, is O(n^2): up to about 5 × 10^9 steps, far too slow.
The input is already sorted, and the problem says so for a reason. With one pointer at each end, you can skip the sort and finish in O(n).
Read the values too. A square is at most 10^8, under the 32-bit limit of 2,147,483,647, so 32-bit integers are enough.