Sorted GCD Pair Queries
Real-world version: Gear Mesh QueriesThe statement here is our own: the same inputs, outputs and technique.
A workshop holds n gear blanks, and blank i has been cut with teeth[i] teeth. For every pair of different blanks i < j, the mesh of that pair is the largest whole number that divides both teeth[i] and teeth[j].
All n * (n - 1) / 2 meshes are written on a card and the card is then sorted into non-decreasing order. Two different pairs that share a mesh value each contribute their own entry, so the card always holds exactly n * (n - 1) / 2 entries.
Answer the batch of queries against that sorted card: for each queries[t] return the entry at position queries[t], counting positions from 0. Return the answers in the order the queries were asked.
Examples
Example 1
- Input
- teeth = [2, 3, 4], queries = [0, 1, 2]
- Output
- [1, 1, 2]
The three pairs mesh at 1, 2 and 1, so the sorted card reads 1, 1, 2 and the three queries read off its three positions in turn.
Example 2
- Input
- teeth = [12, 18, 24, 30], queries = [5, 0, 3, 3]
- Output
- [12, 6, 6, 6]
The six pairs mesh at 6, 12, 6, 6, 6 and 6, so the sorted card reads 6, 6, 6, 6, 6, 12. Position 5 holds 12, position 0 holds 6, and position 3 is asked twice and holds 6 both times.
Example 3
- Input
- teeth = [50000, 25000, 2], queries = [0, 1, 2]
- Output
- [2, 2, 25000]
The pair of large blanks meshes at 25000 and both pairs involving the small blank mesh at 2, so the sorted card reads 2, 2, 25000.
Constraints
- 2 <= n == teeth.length <= 10^5
- 1 <= teeth[i] <= 5 * 10^4
- 1 <= queries.length <= 10^5
- 0 <= queries[t] < n * (n - 1) / 2
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def mesh_queries(teeth: list[int], queries: list[int]) -> list[int]:public int[] meshQueries(int[] teeth, long[] queries)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Find Greatest Common Divisor of ArrayReal-world version: Sprocket Extremes Common DivisorEasy
- Number of Pairs of Interchangeable RectanglesReal-world version: Panes Cut to the Same ShapeMedium
- Find the Number of Subsequences With Equal GCDReal-world version: Matched Gear BenchesHard
- Minimum Deletions to Make Array DivisibleReal-world version: Discarding Tiles Until the Walls FitHard