Ctrl K

Merging Neighbors With a Common Factor

Hard
You are given an array of positive integers values. As long as two **adjacent** numbers share a common divisor greater than 1, replace that pair with a single number: their least common multiple. The process stops when no such pair is left. It can be shown that the final array does not depend on the order of the merges. Return the final array.
Example 1
values=[10, 4, 9, 7, 21] → [20, 63]

10 and 4 merge into 20. 7 and 21 merge into 21, then 9 and 21 merge into 63. 20 and 63 share no factor. Result: [20, 63].

Example 2
values=[3, 5, 15, 2] → [15, 2]

5 and 15 give 15, then 3 and 15 give 15 as well. The remaining 15 and 2 share no factor.

Example 3
values=[1, 1, 7] → [1, 1, 7]

1 shares no factor with anything, so nothing merges.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
  • Every number in the final array is at most 10⁸
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Shared-Factor Group HardMake One From Multiples HardTowns Joined by Big Divisors HardNearest Coprime Ancestor HardWhen Rail Robots Catch Up Hard
loading Python…
Input
values=[10, 4, 9, 7, 21]
Expected
[20, 63]

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