968. Shared Factor Groups

A museum tags each exhibit with a positive integer from nums. Two exhibits are linked if their tag numbers share a common divisor greater than 1. Links chain together: if A is linked to B and B is linked to C, then A, B and C all belong to the same group, even when A and C are not directly linked.

Return the size of the largest group. Two entries with equal values are separate exhibits (equal values greater than 1 are linked to each other). The number 1 has no divisor above 1, so an exhibit tagged 1 always forms a group of size 1 by itself.

Example 1

Input:
nums = [12,35,49,18,77]
Output:
3
Explanation:

12 and 18 share the factor 6 (group of 2); 35, 49 and 77 are tied together through 7 (group of 3), so the largest group has 3 numbers.

Example 2

Input:
nums = [1,1,1]
Output:
1
Explanation:

The number 1 has no factor above 1, so every 1 is alone and the largest group has size 1.

Example 3

Input:
nums = [14,21,10,25,11]
Output:
4
Explanation:

21 and 14 share 7, 14 and 10 share 2, 10 and 25 share 5, chaining four numbers together; 11 shares nothing with them.

Constraints

  • 1 ≤ nums.length ≤ 20000
  • 1 ≤ nums[i] ≤ 105

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(max * log log max + n log max)
Space
O(max + n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…