Problem solution · Python

Sorted GCD Pair Queries

Sorted GCD Pair Queries: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
29 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Sorted GCD Pair Queries, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 29 lines of Python from the credited upstream file 3312.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeSorted GCD Pair Queries · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def gcdValues(self, nums: list[int], queries: list[int]) -> list[int]:    maxNum = max(nums)    # countDivisor[d] := the number of `nums` having `num % d == 0`    countDivisor = [0] * (maxNum + 1)    # countGcdPair[g] := the number of pairs having gcd == g    countGcdPair = [0] * (maxNum + 1)     for num in nums:      for i in range(1, math.isqrt(num) + 1):        if num % i == 0:          countDivisor[i] += 1          if i != num // i:            countDivisor[num // i] += 1     for gcd in range(maxNum, 0, -1):      # There are C(countDivisor[gcd], 2) pairs that have a common divisor      # that's a multiple of `gcd` (including the one that equals to `gcd`).      # So, substract the multiples of `gcd` to have the number of pairs with a      # gcd that's exactly `gcd`.      countGcdPair[gcd] = countDivisor[gcd] * (countDivisor[gcd] - 1) // 2      for largerGcd in range(2 * gcd, maxNum + 1, gcd):        countGcdPair[gcd] -= countGcdPair[largerGcd]     # prefixCountGcdPair[g] := the number of pairs having gcd <= g    prefixCountGcdPair = list(itertools.accumulate(countGcdPair))    return [bisect.bisect_left(prefixCountGcdPair, query + 1)            for query in queries] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗