#3867

Sum of GCD of Formed Pairs

Medium
ArrayMathTwo PointersSimulationNumber TheoryPrefix SumSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

This approach leverages a single pass to compute prefix GCDs while maintaining the maximum value, followed by sorting and pairing, resulting in a more efficient solution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize mx and compute prefixGcd in a single pass over nums.
  2. 2Step 2: Sort the prefixGcd array.
  3. 3Step 3: Pair elements from both ends of the sorted array to compute GCDs.
solution.py10 lines
1def sumGCD(nums):
2    n = len(nums)
3    prefixGcd = []
4    mx = 0
5    for num in nums:
6        mx = max(mx, num)
7        prefixGcd.append(gcd(num, mx))
8    prefixGcd.sort()
9    total = sum(gcd(prefixGcd[i], prefixGcd[n - 1 - i]) for i in range(n // 2))
10    return total

Complexity note: The dominant factor is sorting the prefixGcd array, which is O(n log n). The prefix GCD computation is O(n).

  • 1Prefix GCDs depend on the maximum value seen so far.
  • 2Sorting allows efficient pairing of elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.