Payments app~15 min2s · 256 MBtarget O(q log m) time, O(1) spaceclassic twin: lc-69binary-search
A payments app draws a chart of transaction amounts on a square-root scale, so that a few very large payments do not squash all the small ones. For every amount, the chart needs a bucket number.
The bucket number is the largest whole number s with s × s at most the amount. You may not use a square root function.
Write int_roots(amounts).
n, find the largest whole number s such that s * s <= n.s for each amount, in order.Input: amounts = [17, 16, 0, 1, 99, 1000000000]
Output: [4, 4, 0, 1, 9, 31622]Take the amount 17. Search for the first whole number s whose square is above 17. The window [lo, hi) starts as [0, 18), because 17 + 1 = 18 is certainly too large.
| Step | lo | hi | mid | mid × mid | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 18 | 9 | 81 | 81 > 17, so hi = 9 |
| 2 | 0 | 9 | 4 | 16 | 16 <= 17, so lo = 5 |
| 3 | 5 | 9 | 7 | 49 | 49 > 17, so hi = 7 |
| 4 | 5 | 7 | 6 | 36 | 36 > 17, so hi = 6 |
| 5 | 5 | 6 | 5 | 25 | 25 > 17, so hi = 5 |
| end | 5 | 5 | the first s with a square above 17 is 5, so the answer is 4 |
The amount 16 gives 4, because 16 is a perfect square. The amount 0 gives 0, and 1 gives 1. The amount 99 gives 9, and 10^9 gives 31,622.
Input: amounts = []
Output: []An empty list returns an empty list.
Input: amounts = [0, 1, 2, 3, 4]
Output: [0, 1, 1, 1, 2]The roots are 0, 1, 1, 1 and 2. The root changes only at the perfect squares 0, 1 and 4.
0 ≤ amounts.length ≤ 100,0000 ≤ amounts[i] ≤ 1,000,000,000 (minor units)Counting up from 0 until the square passes the amount takes about 31,600 steps for an amount of 10^9. For 100,000 amounts that is about 3 × 10^9 steps. A binary search over the possible roots needs about 30 steps per amount, because the answer is somewhere in a range of a billion numbers.