Ctrl K

All Linked by Common Factors

Hard
You are given an integer array values. You may step from position i to position j (i ≠ j) when values[i] and values[j] have a common divisor greater than 1. Return True if every position can reach every other position in one or more steps, and False otherwise. An array with a single element counts as linked.
Example 1
values=[10, 21, 35] → True

10 and 35 share 5, 21 and 35 share 7. You get from 10 to 21 through 35, so everything is linked.

Example 2
values=[4, 8, 9, 27] → False

There are two separate groups: {4, 8} sharing 2 and {9, 27} sharing 3.

Example 3
values=[6, 1] → False

1 shares no divisor above 1 with anything, so it can never be reached.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Shared-Factor Group HardTowns Joined by Big Divisors HardSorting With Shared-Divisor Swaps HardGroups With a Small LCM HardMake One From Multiples Hard
loading Python…
Input
values=[10, 21, 35]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 132 tests on the server, hidden ones included.