2197. Replace Non-Coprime Numbers in Array #2180
-
Topics: You are given an array of integers
Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to Two values Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to repeatedly replace any two adjacent non-coprime numbers in an array with their Least Common Multiple (LCM) until no adjacent non-coprime pairs remain. The solution involves efficiently processing the array while ensuring that any merges are handled in a way that might require further merges with previous elements. Approach
Let's implement this solution in PHP: 2197. Replace Non-Coprime Numbers in Array <?php
/**
* @param Integer[] $nums
* @return Integer[]
*/
function replaceNonCoprimes($nums) {
$stack = [];
foreach ($nums as $num) {
$current = $num;
while (!empty($stack)) {
$top = end($stack);
$g = gcd($current, $top);
if ($g == 1) break;
array_pop($stack);
$current = ($current * $top) / $g;
}
$stack[] = $current;
}
return $stack;
}
/**
* @param $a
* @param $b
* @return int|mixed
*/
function gcd($a, $b) {
while ($b != 0) {
$temp = $b;
$b = $a % $b;
$a = $temp;
}
return $a;
}
// Test cases
$nums1 = [6,4,3,2,7,6,2];
print_r(replaceNonCoprimes($nums1));
// Output: [12, 7, 6]
$nums2 = [2,2,1,1,3,3,3];
print_r(replaceNonCoprimes($nums2));
// Output: [2, 1, 1, 3]
?> Explanation:
This approach efficiently processes the array by leveraging a stack to handle merges in a left-to-right manner, ensuring that all possible adjacent non-coprime pairs are merged correctly. The algorithm efficiently handles chain reactions caused by merges by repeatedly checking the merged value against the previous elements in the stack. The time complexity is linear with respect to the input size, making it suitable for large arrays. |
Beta Was this translation helpful? Give feedback.
We need to repeatedly replace any two adjacent non-coprime numbers in an array with their Least Common Multiple (LCM) until no adjacent non-coprime pairs remain. The solution involves efficiently processing the array while ensuring that any merges are handled in a way that might require further merges with previous elements.
Approach