Minimum Deletions to Make Array Divisible Problem
Description
LeetCode Problem 2344.
You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.
Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1.
Note that an integer x divides y if y % x == 0.
Example 1:
Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]
Output: 2
Explanation:
The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.
We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].
The smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.
It can be shown that 2 is the minimum number of deletions needed.
Example 2:
Input: nums = [4,3,6], numsDivide = [8,2,6,10]
Output: -1
Explanation:
We want the smallest element in nums to divide all the elements of numsDivide.
There is no way to delete elements from nums to allow this.
Constraints:
1 <= nums.length, numsDivide.length <= 10^51 <= nums[i], numsDivide[i] <= 10^9
Solution
Approach: GCD + Sorting
An element of nums can divide every value of numsDivide exactly when it divides their greatest common divisor g. So the question becomes: how many of the smallest elements of nums must go before we reach one that divides g?
Compute g by folding gcd over numsDivide, sort nums, and return the index of the first element that divides g. If there is none, return -1.
Complexity: O(m + log M + n log n) time, where n and m are the lengths of nums and numsDivide and M is the largest value in numsDivide; O(1) extra space besides sorting.
from math import gcd
class Solution:
def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:
x = numsDivide[0]
for v in numsDivide[1:]:
x = gcd(x, v)
nums.sort()
for i, v in enumerate(nums):
if x % v == 0:
return i
return -1