Problem Description
Given two arrays, nums and numsDivide, we need to delete a minimum number of elements from nums such that the smallest remaining element divides all elements of numsDivide. If it’s impossible to achieve this, return -1.
Key Insights
- The smallest element in nums must divide every element in numsDivide.
- The greatest common divisor (GCD) of numsDivide is crucial because any candidate from nums must be a divisor of the GCD.
- Compute the GCD of numsDivide; any valid candidate from nums must divide this GCD.
- Sort nums in ascending order and iterate until finding the first element that divides the GCD.
- The number of deletions corresponds to the index of that candidate in the sorted nums array.
Space and Time Complexity
Time Complexity: O(m + n log n)
Space Complexity: O(n)
Solution
- Compute the GCD of all elements in numsDivide.
- Sort the nums array.
- Iterate over the sorted nums and count deletions until you find the first element (smallest candidate) that divides the GCD.
- Return the count of deletions; if no candidate is found, return -1.