1439. Strongest Common Factor

Medium3.5 points estimatedNumber TheoryCountingArray

A logistics team wants to split two parcels from a shipment into identical equal-sized boxes, and the box size must divide both parcel weights. Given the list nums of parcel weights, return the largest value of gcd(nums[i], nums[j]) over all index pairs i < j, as an int. A weight that appears twice already gives a pair whose gcd equals that weight. Checking every pair is too slow for the largest inputs; instead count how often each value occurs and test candidates g from the maximum value downwards, asking whether at least two elements are multiples of g. Intended cost is O(V log V) time and O(V) space, where V is the largest value.

Example 1

Input:
nums = [6,10,15]
Output:
5
Explanation:

gcd(10, 15) = 5 beats gcd(6, 10) = 2 and gcd(6, 15) = 3.

Example 2

Input:
nums = [4,9,25]
Output:
1
Explanation:

The values are pairwise coprime, so the best gcd is 1.

Constraints

2 ≤ n ≤ 105 (n is the length of nums)

1 ≤ nums[i] ≤ 2 * 105

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n + V log V)
Space
O(V)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…