To efficiently count pairs with a specific GCD value in an array, use the inclusion-exclusion principle: count all pairs where both elements are divisible by g, then subtract pairs where both elements are divisible by multiples of g (2g, 3g, etc.). This approach reduces complexity from O(n²) to O(m log m) where m is the maximum array value, making it feasible for large inputs (n up to 10^5).
Deep Dive
Prerequisite Knowledge
- No data available.
Where to go next
- No data available.
Deep Dive
Leetcode Daily . Sorted GCD Pair Queries
Added:Hey all uh let's solve today's lead code daily which says sorted GCD pair queries.
I haven't solved it before.
Let me reset the timer and start uh reading the problem. Let's see how we can approach it.
Given an integer array nums lengthen integer array queries.
GCD pairs denote array calculating pairs for all the nums of I and nums of J. I less than J and then sorting these values in ascending order.
We are given queries. We need to find element that queries of five in gcdps.
Got it?
And we need to return that array answer.
Answer is the value at GCD pairs of query of okay.
What are the constraints?
* length 10^ 5 of 5 into 10^ 4 of can be up to n into n - think about Good job. So, Yeah.
So let me explain the problem first. We are given an arrays and we are have having some queries and for every pair I comma J pair I less than J. Now in nums we need to find the GCD.
Now once we get the GCD we need to sort them.
After sorting we need to uh we are having some queries and we need to get the value of uh sorted gcd at the query index.
So we are having suppose from SAS three and four.
We find GCD for all the nums.
uh gcd of 2a 3 is 1. GCD of 2a 4 is 2.
GCD of 3a 4 is 5. Now we sort this gcd array 1a 1a 2 and H once we sort we are having some queries.
So we need to find GCD at queries of five.
For uh query zero the output would be one. For query one output would be one.
For query two output would be two.
So answer would be 1 comma 1 comma 2. So for the given there is 32 should be two.
That's all we focus on how to find smallest GCD at every query.
Suppose if we are given query two we need to find second smallest GCD in the given array.
So now what would be the brute force approach you can think of?
Uh when you see all the I comma J you would think of generating all the pairs and find the GCD push back GCD for all the pairs and then sort the GCD and get answer for every query and return that answer array.
Right?
Now what would be the complexity?
Suppose for the given n it is still 10^ 5 and queries are still n into n - 1 by 2.
So if we take 10^ 5 10^ 5 into 10^ 5 - 1 by 2 it is uh into billions it is not uh optimal.
So we need to forget about uh computing gcd for every pair and sorting it.
So uh now just to understand like what is uh where is the optimization we can make currently we are uh what we are doing we are uh creating pairs we are going to each pair in the nums and then generating gcd then we are sorting and finding it.
So the issue is not finding the GCD but generating in a pairs.
So do we need to check each and every pair suppose uh there is a repetitive2 array.
Suppose we have 4a 4. GCD of 4a 2 4a 1 4a 2 4a 1 is always same.
So instead of uh finding GCD for all the pairs uh can't we create a frequency map and find GCD for all the pairs in the frequency map? So we just need all the possible GCDs in the array ID. So 4a 2 4a 1 4a 2 4a 1 this is a repetitive pattern which does not even make sense and gcd of 4a 4 is four itself.
So there is uh no point of calculating gcd for the rep elements. So let me create map of the given nums.
Now this will be reduced to commun.
Yeah.
Now this is enough. Now instead of generating pairs uh can we simply know that how many pairs have GCD1 how many pairs have GCD2 so on uh if it is possible we don't need to make a huge array so let me think in the terms So for every possible GCD I need to find how many pairs uh can give that GCD.
This feels strange.
Can we I feel that both will give exact uh the same information. But what would be the final output array is the question.
Let me take a sorted area first. 1 25.
Yeah. Now I have uh repetitive ones and twos. Now if I find GCD it is the same one 1 1 1 2 5 uh if I store the GCD count it would look like this 1 is 2 2 is 2 * 5 is one time in this way we can store the count and in ascending manner ascending living order panel instead of having entire array of answer for GCP.
So let me check uh what would be complexity of this.
Suppose uh it is still 10^ 5 and possible values are still from 1 to 10^ 5.
Now we are having map. It is off in operation. In the worst case we are not doing any sorting.
So uh it would be 10^ five operations.
Yeah, this is this satisfies the given constraints.
Uh can I think of any better approach or shall we proceed with this?
Now we are knowing that how many pairs have GCD 5, GCD2, GCD 1.
Can we count them without looking every pair?
We know that how many pairs have GCD K.
Uh we instead of taking every pair to compute GCD.
Let me think of better approach here.
I'm trying to think in terms of divisibility if like I have 12 and 18 both are divisible by 6 GCD 6.
So until uh all the numbers are not divisible are not divisible by six.
So uh uh we can get all the numbers which will visible by six.
Uh so their count suppose I have uh 6 12 18 24.
I have four numbers which are divisible by six. Now to get gcd6 I need to take pairs any two pairs of this.
So what would be the case?
Uh uh uh we need to choose two numbers from this 4 Z2. We can do combination.
Wait. Ah but GCD of 6, 12 is not six. It is three.
Right.
I missed this.
It is easy to count in this div but the GCD is not exactly the same uh lowest divisor.
It might vary. So you need to understand key difference.
TCD would be 12 for 12 and 24. base.
Uh oh yes.
Now suppose uh yeah I understood the problem. Now I have GCD 12 24 uh 18 so on.
Now for the given pair uh I take I take any pair in this. Now to get the GCD we need to know we need to include that element or exclude that element.
we can't generate all the pairs and we can't count how many pairs has this. So we need to know whether we need to include [clears throat] it or exclude it to get the given GCD.
Uh so this is the efficient way.
So uh we can uh try reversive and inclusion occlusion for that. Uh I'm thinking I'm just thinking in terms like if I need uh k smallest or largest uh can I count how many answers will be equals to value mean instead of generating all the gcds how many answers will be equals to the gcd There you go.
Right.
So number of pairs are n into n minus 1 by 2. This will be happening for everything.
So six has uh four uh divisible values. So number of things will be 4 into 4 - 1 by 2 which is 6.
Huh?
This makes sense. Now why should we consider multiples is because like if I take 6 and 12 they both are still divisible by uh 2 and 3.
So it gets counted with two also.
Suppose two uh I take 48 the GCD is four. But now if I take 2, 6, the GCD is two.
Uh now our count contains uh GCD can be 2 4 6 and 8.
Now if I want to remove that extra base.
Now for all the things which are divisible by two towards right we find uh so in this way I think uh it is let me What's the right approach?
So we travel all elements from uh max what can the GCD be from 1 to max value.
So we traverse from one to max.
What happens?
Suppose if G I I want GCDS2.
We Oh, right, right. We can't find the GCD of the multiples of two. uh we need to traverse from right to left in that case.
Makes sense.
Now if I move backward I'll be having GCD of all the divisor. So I can subtract them.
H now to find GCD of two you need to do GCD of 2 minus GCD of multiples of two. This is simple inclusion exclusion principle.
Yeah.
This is the algorithm. Let me assess complexity for this.
We are it.
What is the complexity of this?
After finding GCD, we find the cons inclusion exclusion.
But we should also need Wait. Uh I think I'm missing something here.
We got all the GCDs.
Now I need to build a sorted array instead of building sorted array.
Why can't have uh why I can't have a prefix count?
Suppose uh uh uh uh after this I might get some GC array like 1 comma 1 comma 2A 2a 5. Instead of like doing a sorted array, I can instead store this CD as 1 comma 2 1 M [snorts] got it.
I get all the GCD pairs.
I can have that index for the GCD pairs and I can find the next possible GCD pair by doing binary search.
Oh yeah, that makes sense. Now the complexity is we find all the gcds which takes uh of M. M is the maximum value and to do binary search to find next possible uh there we do we need of login I think it's the most optimal way is there any other way let me think this is interesting Actually no I don't think there is no other optimal way. So first uh let me find maximum value element of store begin.
I got sorted array. I need frequency array of values are long. Let me take long one.
Let's see zero h.
No, I'll do frequency map in nums.
uh frequency of num++.
I have frequency map. Now next what I need to do I need to traverse from right to left for in g = to max greater than or = 0 - yeah I traverse towards left oh g can't be zero it must be one like one is the maximum minimum GCD that we get. Yeah, sorry.
Now, now I need to get count for each pair.
Let me take zero.
And now I need to get all the devices for current G and while K less than max K plus equals to G.
all the devices count plus equals to frequency of okay.
So I got count of all devices.
No total pairs possible. Oh, we need one more array here to check inclusion.
Exclusion exclude of MX + 1 comma 0 I'm thinking it has bounds. There might be values less than this but in the worst case it can be t + mx + 1.
Now exclusion exclusion of current g will be equals to count star count minus 1 by 2 Wait. Uh, I took in long.
Yeah, now it makes sense.
Now I need to do I need to compute uh prefix counts, right? Yeah, I need to do cumulative count vector of long long prefix and I need to get value set prefix values again I need to traverse from left to right now because I'm doing prefix previously I'm doing exclusion so I try from right to left.
If inclusion exclusion of G is greater than zero, now we are having pairs.
Uh I need some sum is zero long long.
Now I add the inclusion exclusion to prefix sum inclusion expression of G.
Now prefix dot push back of some and values dot pushore uh uh tag of g makes sense.
Now the only thing I need to worry about getting for each query.
Sorry, it's early in the morning. So I'm feeling some discomfort to ride the boat. Let's go.
Uh uh uh uh long long quil inquiries I somehow like this problem very much it feels lot of clear intuition I don't know prefix X on top.
What should be the value?
Where should I need index. So I'll go with I think uh this makes sense. I just push back the value add index index and I got this. I just return the result.
Let me check the answer. One second.
Max frequency max.
What is the I to karma here? Not Same here.
Lot of syntax issues.
Oh man.
Oh my god.
That's why we need a good sleep after lot.
What is name is simply Wait, I'm not excluding it. I'm just including K equals to start G.
Okay. supposed to change x of g = to x of k. Now I excluded all the multiples. Now I think it would be right answer.
Let me submit this.
Yeah, this worked.
So basically uh in a simple terms instead of finding all the pairs which is uh of square we just optimized it to keep it to 100 by focusing on divisibility.
The only thing I think we need to think here is do we need to count by value instead of pair and this we will see when inclusion exclusion would be coming by practice and it's a great understanding why we need to include and exclude.
Bye.
Related Videos

TOP 15 Data compression Interview Questions and Answers 2019 Part-2 | Data compression | Wisdom jobs
wisdomjobs
281 views•2019-06-28

CTS 158: 802.11w Management Frame Protection
ClearToSend
4K views•2019-02-04

NDSS 2019 Send Hardest Problems My Way: Probabilistic Path Prioritization for Hybrid Fuzzing
NDSSSymposium
496 views•2019-04-02

How realistic is Cities: Skylines?
CityBeautiful
159K views•2019-02-14

GUIs & TUIs: Choosing a User Interface for Your Python Project | Real Python Podcast
realpython
2K views•2025-04-04

The OSI Model - Explained by Example
hnasr
225K views•2019-05-12

Cloud Computing - Introduction
elithecomputerguy
98K views•2019-10-07

From Traveler's Dilemma to Dynamic Routing | Demystifying Networking
IITBombayJuly
5K views•2019-08-04
Trending

WOW! Judge TURNS THE TABLES on Trump in His OWN $10B LAWSUIT!!!
MeidasTouch
197K views•2026-07-23

Playstation NO DISC/NO BUY Fight Is Over...
DavidJaffeGames
4K views•2026-07-23

Steam and Xbox Just Dropped The Hammer On PlayStation
OhNoItsAlexx
9K views•2026-07-23

Americans Confused in Australia for 17 Minutes Straight
IWrocker
17K views•2026-07-23