Answer Connectivity Queries Between Shards Sharing a Large Common Divisor
Last updated: November 29, 2026
Quick Overview
Shards are labeled 1 to n, and shards x and y are directly linked if they share a common divisor strictly greater than threshold. Given many (a, b) queries, return for each whether a and b are connected through any chain of links.
0
0
0 solved
Shards are labeled 1 to n, and shards x and y are directly linked if they share a common divisor strictly greater than threshold. Given many (a, b) queries, return for each whether a and b are connected through any chain of links.
Google onsites like problems where the graph is implicit and far too dense to build, and this one has up to n^2 / 2 edges if you enumerate pairs. The interviewer is checking that you union each candidate divisor with its multiples, a sieve-style trick, and that you can bound the work with a harmonic sum.
What the Interviewer Expects
- Recognizes that enumerating all pairs is quadratic
- Links each divisor d above the threshold with all its multiples
- Explains why that preserves exactly the same components
- Bounds the total work with the harmonic series
- Answers each query with two finds
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if the labels are arbitrary large values rather than 1 to n?
- Support a threshold that changes per query; can you process queries offline?
- Return the size of the component for each query instead of a boolean.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
n,threshold, and a list of query pairs with values in1..n. - Direct link:
gcd(x, y) > threshold. - Output: list of booleans, one per query.
- With
threshold = 0, every pair shares...
High-Level Design
Two shards share a divisor d > threshold exactly when both are multiples of d. So instead of checking pairs, for each d from threshold + 1 to n, union d with 2d, 3d, .... All multiples o...