Problem
You are given a 0-indexed integer array nums
containing positive integers.
Your task is to minimize the length of nums
by performing the following operations any number of times (including zero):
- Select two distinct indices
i
andj
fromnums
, such thatnums[i] > 0
andnums[j] > 0
. - Insert the result of
nums[i] % nums[j]
at the end ofnums
. - Delete the elements at indices
i
andj
fromnums
.
Return _an integer denoting theminimum length of _nums
after performing the operation any number of times.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
Solution
Method 1 – GCD Reduction
Intuition
The operation nums[i] % nums[j]
can only reduce the array if the result is nonzero. The process is similar to repeatedly applying the Euclidean algorithm, which ultimately reduces all numbers to their greatest common divisor (GCD). The minimum possible length is the number of unique GCDs in the array after all reductions.
Approach
- Compute the GCD of all elements in the array.
- If all elements are multiples of the GCD, the array can be reduced to length 1.
- Otherwise, the minimum length is the number of unique GCDs that cannot be further reduced.
- For this problem, the answer is always 1 if any operation can be performed, otherwise the length of the array.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, for computing the GCD of all elements. - 🧺 Space complexity:
O(1)
, only a few variables are used.