Install our extension to search inside any video instantly.

Sorted GCD Pair Queries | LeetCode 3312 - Python

Added:
672 views37likes19:17impoldevOriginal Release: 2026-07-17

This video presents an efficient algorithm for solving the Sorted GCD Pair Queries problem (LeetCode 3312) by avoiding the O(n²) complexity of building the GCD pairs array directly. The solution involves five key steps: (1) building a frequency array of the input numbers, (2) transforming it to count elements divisible by each index using a sieve-like approach, (3) calculating pairs where both numbers are divisible by each index using combinatorics (n choose 2), (4) computing exact GCD counts by subtracting multiples, and (5) applying prefix sums to enable binary search queries. The time complexity is O(max(nums) * log(max(nums)) + Q * log(max(nums))), making it suitable for large inputs where n can be up to 10^5.