Online store~40 min2s · 256 MBtarget O(V log log V + n log V α(n)) time, O(V + n) spaceclassic twin: lc-952union-find
An online store sells spare parts. Every part has a different whole-number code. Two parts belong to the same series when their codes share a prime factor. Small primes, such as 2 and 3, mark broad categories and mean little.
So the store only counts a shared prime of at least k. A family is a set of parts linked through such shared primes, one link after another.
Your team lead asks: How many parts are in the largest family?
Write largest_family(codes, k).
codes is a list of different whole numbers, each from 1 to 100,000.k is the smallest prime that counts as a series number.k divides both. The code 1 has no prime factor, so it is never linked.Input: codes = [6,10,15,21,35,49,11], k = 5
Output: 5The solution splits each code into primes. For each prime of at least k it joins the code with the first code that used that prime.
| Code | Primes of at least 5 | Family after joining |
|---|---|---|
| 6 | none | 6 |
| 10 | 5 | 10 |
| 15 | 5 | 10, 15 |
| 21 | 7 | 21 |
| 35 | 5, 7 | 10, 15, 21, 35 |
| 49 | 7 | 10, 15, 21, 35, 49 |
| 11 | 11 | 11 |
The largest family has 5 codes.
Input: codes = [6,10,15,21,35,49,11], k = 2
Output: 6Now the primes 2 and 3 count as well, so the code 6 joins the big family. Only 11 stays alone.
Input: codes = [6,10,15,21,35,49,11], k = 8
Output: 1Only the code 11 has a prime of 8 or more, and no other code shares it. Every family has one part.
1 ≤ len(codes) ≤ 20,000, all codes different1 ≤ codes[i] ≤ 100,0002 ≤ k ≤ 100,000Comparing every pair means about 200,000,000 pairs, and each pair needs a divisor check. Instead, factor each code once. A number up to 100,000 has at most six different primes.