Ctrl K

Pair GCDs by Sorted Position

Hard
You are given an array values of n positive integers. Take every pair of indices i < j and compute the greatest common divisor of values[i] and values[j]. That gives n · (n - 1) / 2 numbers; sort them in non-decreasing order. You are also given an array positions. For each positions[k], find the number at that position (0-based) in the sorted list of gcds, and return the answers in the same order.
Example 1
values=[6, 9, 4], positions=[0, 1, 2] → [1, 2, 3]

The pair gcds are (6, 9) → 3, (6, 4) → 2, (9, 4) → 1. Sorted, that is [1, 2, 3].

Example 2
values=[8, 12, 8, 5], positions=[5, 0, 4, 4] → [8, 1, 4, 4]

The six pairs give gcds 1, 1, 1, 4, 4, 8 in sorted order. Position 5 holds 8, position 0 holds 1 and position 4 holds 4. Positions may repeat.

Example 3
values=[7, 7], positions=[0] → [7]
Constraints
  • 2 ≤ n = len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 5 · 10⁴
  • 1 ≤ len(positions) ≤ 10⁵
  • 0 ≤ positions[k] < n · (n - 1) / 2
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsK-th Postage With One Stamp Type HardEven Piles of Cards EasyPhoto Frames of the Same Shape MediumCoprime Digit Pairs EasyPrimes Along Grid Rays Medium
loading Python…
Input
values=[6, 9, 4], positions=[0, 1, 2]
Expected
[1, 2, 3]

Run checks the first 3 tests in your browser. Submit checks all 45 tests on the server, hidden ones included.