Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Replace Non-Coprime Numbers in Array

XPChallenge Points: 30
levelLevel: Hard

You are given an array nums. You must repeatedly replace adjacent non-coprime numbers using the rule:

  1. Find any two adjacent numbers whose GCD > 1
    → These numbers are non-coprime.

  2. Remove both numbers.

  3. Insert their LCM in the same position.

  4. Repeat until no adjacent pair has GCD > 1.

The final array is guaranteed to be the same regardless of which valid pair you merge first.

The final values will always be ≤ 10⁸.

Definitions:
Two numbers x and y are non-coprime if:

GCD(x, y) > 1
Example 1:

Input: nums = [6,4,3,2,7,6,2]

Output: [12,7,6]

Explanation:

(6, 4) → merge → LCM(6,4)=12 → [12,3,2,7,6,2] (12, 3) → merge → 12 → [12,2,7,6,2] (12, 2) → merge → 12 → [12,7,6,2] (6, 2) → merge → 6 → [12,7,6] No more pairs → result is [12,7,6].

Example 2:

Input: nums = [2,2,1,1,3,3,3]

Output: [2,1,1,3]

Explanation:

(3,3) → merge → [2,2,1,1,3,3] (3,3) → merge → [2,2,1,1,3] (2,2) → merge → [2,1,1,3] Done → final: [2,1,1,3].

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result