Parcel-delivery app~15 min2s · 256 MBtarget O(n log m) time, O(1) spaceclassic twin: lc-1979number-theory
A parcel-delivery app ships cartons of gift sweets. Each carton holds a different number of identical sweets. The packers want to repack every carton into identical bags: the same number of sweets in every bag, and none left over in any carton.
Your team lead asks: "What is the largest bag size that works?" A bulk order can have 100,000 cartons, and a carton holds up to 1,000,000,000 sweets.
Write largest_bag_size(cartons).
cartons[i] is the number of sweets in carton i.Input: cartons = [12, 18, 30]
Output: 6Take the cartons two at a time. Euclid's rule says that the largest size dividing both a and b is the same as the largest size dividing b and a mod b. Repeat until the second number is 0.
| Step | Pair | Remainders | Largest common size |
|---|---|---|---|
| 1 | 12 and 18 | 18 mod 12 is 6, then 12 mod 6 is 0 | 6 |
| 2 | 6 and 30 | 30 mod 6 is 0 | 6 |
Bags of 6 leave nothing over in any carton: 2, 3 and 5 bags.
Input: cartons = [7, 13]
Output: 113 mod 7 is 6, 7 mod 6 is 1, and 6 mod 1 is 0. The two cartons share no size above 1.
Input: cartons = [40]
Output: 40One carton: the whole carton is one bag.
1 ≤ len(cartons) ≤ 100,0001 ≤ cartons[i] ≤ 1,000,000,000A bag cannot be larger than the smallest carton, so you could try every size from the smallest carton down to 1. That is up to a billion tries, for each of up to 100,000 cartons, which never finishes. Listing the divisors of the smallest carton is faster, but a list can still have over a thousand divisors, and each one is tested on every carton. The numbers fit in an int, and so does every remainder, but a product of two cartons would not.