Sum of GCD of Formed Pairs Problem
#3867
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3867.
You are given an integer array nums of length n.
Construct an array prefixGcd where for each index i:
- Let
mx_i = max(nums[0], nums[1], ..., nums[i]). prefixGcd[i] = gcd(nums[i], mx_i).
After constructing prefixGcd:
- Sort
prefixGcdin non-decreasing order. - Form pairs by taking the smallest unpaired element and the largest unpaired element.
- Repeat this process until no more pairs can be formed.
- For each formed pair, compute the
gcdof the two elements. - If
nis odd, the middle element in theprefixGcdarray remains unpaired and should be ignored.
Return an integer denoting the sum of the GCD values of all formed pairs.
The term gcd(a, b) denotes the greatest common divisor of a and b.
Example 1:
Input: nums = [2,6,4]
Output: 2
Explanation:
Construct prefixGcd:
i nums[i] mx_i prefixGcd[i]
0 2 2 2
1 6 6 6
2 4 6 2
prefixGcd = [2, 6, 2]. After sorting, it forms [2, 2, 6].
Pair the smallest and largest elements: gcd(2, 6) = 2. The remaining middle element 2 is ignored. Thus, the sum is 2.
Example 2:
Input: nums = [3,6,2,8]
Output: 5
Explanation:
Construct prefixGcd:
i nums[i] mx_i prefixGcd[i]
0 3 3 3
1 6 6 6
2 2 6 2
3 8 8 8
prefixGcd = [3, 6, 2, 8]. After sorting, it forms [2, 3, 6, 8].
Form pairs: gcd(2, 8) = 2 and gcd(3, 6) = 3. Thus, the sum is 2 + 3 = 5.
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Simulation
Follow the statement. Track the running maximum mx and store gcd(nums[i], mx) in prefixGcd. Sort it, then pair the i-th smallest with the i-th largest for i < n / 2 and add up the gcds of the pairs; the middle element of an odd-length array is skipped.
Complexity: O(n log M + n log n) time and O(n) space, where M is the largest value.
from math import gcd
class Solution:
def gcdSum(self, nums: List[int]) -> int:
n = len(nums)
prefix_gcd = [0] * n
mx = 0
for i, x in enumerate(nums):
mx = max(mx, x)
prefix_gcd[i] = gcd(x, mx)
prefix_gcd.sort()
return sum(gcd(prefix_gcd[i], prefix_gcd[-i - 1]) for i in range(n // 2))