Bank app~15 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting
A banking app lists the entries of a statement by posting time, earliest first. Late-arriving entries land out of place.
Every night a tidy-up sweeps the list from top to bottom. It looks at each neighbouring pair, and swaps the two entries when the upper one has the later time. It repeats the sweep on the next night until a sweep swaps nothing.
How many nights does the tidy-up make at least one swap? The team plans the job from that number.
Write bubble_passes(times).
times[i] is the posting time of the entry in row i, in seconds.i and i + 1 when times[i] > times[i + 1].Input: times = [30, 10, 40, 20, 50, 25]
Output: 3| Sweep | List after the sweep | Swaps |
|---|---|---|
| 1 | [10, 30, 20, 40, 25, 50] | 3 |
| 2 | [10, 20, 30, 25, 40, 50] | 2 |
| 3 | [10, 20, 25, 30, 40, 50] | 1 |
A fourth sweep would swap nothing, so only 3 sweeps count.
Input: times = [9, 4, 7, 2]
Output: 3The entry with time 2 starts in row 3 and moves up one row in each sweep, so it needs 3 sweeps.
Input: times = [1, 2, 3]
Output: 0The list is already in order, so no sweep swaps anything.
0 ≤ times.length ≤ 100,000 (statement entries)0 ≤ times[i] ≤ 1,000,000,000 (seconds)Running the sweeps costs about n sweeps of n steps each, which is up to 10^10 steps at n = 100,000 when the list is in reverse order. Sorting once costs about n log n, which is under 2 × 10^6 comparisons.