Monitoring~15 min2s · 256 MBtarget O(n log m) time, O(1) spacenumber-theory
A monitoring dashboard receives heartbeats from an agent. Each heartbeat has a time in seconds since the agent started. The dashboard wants to cut time into equal ticks of t seconds, so that every heartbeat falls at the same place inside its tick.
Your team lead asks for the largest tick length that works. If every heartbeat arrives at the same second, any tick works, and there is no largest one.
Write largest_tick(times).
times[i] is the time of heartbeat i, in seconds, in any order. Times can repeat.t works when all the times leave the same remainder when divided by t.t that works. If every time is equal, return 0.Input: times = [14, 38, 26, 50]
Output: 12Two times leave the same remainder when divided by t exactly when t divides their difference. So t must divide the difference between the first time and every other time. The largest such t is the greatest common divisor of those differences.
| Time | Distance from 14 | Greatest common divisor so far |
|---|---|---|
| 14 | 0 | 0 |
| 38 | 24 | 24 |
| 26 | 12 | 12 |
| 50 | 36 | 12 |
With t = 12, every time leaves the remainder 2. A tick of 24 fails: 26 leaves 2 and 14 leaves 14.
Input: times = [7, 7, 7]
Output: 0All times are equal, so every tick length works and there is no largest.
Input: times = [5, 8]
Output: 3The difference is 3, and the largest tick that divides it is 3.
1 ≤ length of times ≤ 10^50 ≤ times[i] ≤ 10^9Trying every tick length up to the largest difference costs up to 10^9 steps, and each try checks every time. That is far beyond what 2 seconds allow.
The greatest common divisor of two numbers up to 10^9 takes about 40 steps. Doing it once for each of 10^5 times costs about 4 x 10^6 steps. All values and differences are at most 10^9, so a 32-bit integer holds them.