Ad platform~25 min2s · 256 MBtarget O(q × rounds) time, O(1) spacebinary-search
An ad platform sells square banner slots. A designer gives the area of a slot as a whole number of square units, and the layout tool needs the length of its side.
The tool cuts the side off after six decimal places, and it stores the cut value as a whole number of millionths. A side of 3.162277 units is stored as 3162277. Many slots arrive in one batch.
Write square_roots(areas).
areas[i] is the area of one square slot.a, return the largest whole number k whose side k / 1,000,000 still fits: k × k is at most a × 10^12.Input: areas = [10, 4, 2]
Output: [3162277, 2000000, 1414213]The side of an area of 10 is 3.16227766..., which is cut off to 3.162277, so the answer is 3162277. The side of 4 is exactly 2, so the answer is 2000000.
Search the side as a real number, between 0 and the area. The check on a side x is whether x × x is at least 10.
| Round | lo | hi | mid | mid × mid | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 10 | 5 | 25 | at least 10, so hi = 5 |
| 2 | 0 | 5 | 2.5 | 6.25 | below 10, so lo = 2.5 |
| 3 | 2.5 | 5 | 3.75 | 14.0625 | at least 10, so hi = 3.75 |
| 4 | 2.5 | 3.75 | 3.125 | 9.765625 | below 10, so lo = 3.125 |
| 5 | 3.125 | 3.75 | 3.4375 | 11.81640625 | at least 10, so hi = 3.4375 |
| 6 | 3.125 | 3.4375 | 3.28125 | 10.7666015625 | at least 10, so hi = 3.28125 |
After 100 rounds, lo is 3.162277660168379. In millionths that is 3162277.66, and cutting it off gives 3162277.
Input: areas = [1000000]
Output: [1000000000]The side of the largest area is exactly 1,000 units, which is 1,000,000,000 millionths.
Input: areas = [1, 100, 3]
Output: [1000000, 10000000, 1732050]The sides of 1 and 100 are exact: 1 and 10 units. The side of 3 is 1.7320508..., which is cut off to 1.732050.
1 ≤ areas.length ≤ 30,0001 ≤ areas[i] ≤ 1,000,000The side is at most 1,000 units, so the answer is at most 10^9, which fits in a 32-bit integer. But k × k can reach 10^18, which needs a 64-bit integer in Java and C++. Counting up in millionths takes up to 10^9 steps for one area, which is far too slow for 30,000 areas.