Skip to content
BytePatterns

Largest Group by Shared Factor

HardUnion-Find#union-find#prime-factors~45m

Problem

You are given a list of distinct positive integers. Two numbers are linked when they share a common factor greater than 1, and links chain, so numbers that are linked through others belong to the same group. Return the size of the largest group.

Examples

Input:  nums = [4, 6, 15, 35]
Output: 4
Why:    4 and 6 share 2, 6 and 15 share 3, 15 and 35 share 5, so all four form one group
Input:  nums = [20, 50, 9, 63]
Output: 2
Why:    20 and 50 share 2 and 5, 9 and 63 share 3, and nothing links the two pairs
Input:  nums = [1, 7]
Output: 1
Why:    edge case, 1 has no factor greater than 1, so every group has a single number

Hints

0 / 3

Stuck on the idea rather than the code? Union by Rank or Size covers it.