Minimum Deletions to Make Array Divisible - Problem
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: An integer x divides y if y % x == 0.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,3,2,4,6,7,4], numsDivide = [9,3,12,6]
›
Output:
2
💡 Note:
We need to find the smallest element in nums that divides all elements in numsDivide. After sorting nums = [2,2,3,4,4,6,7], we test: 2 doesn't divide 9, but 3 divides all elements (9÷3=3, 3÷3=1, 12÷3=4, 6÷3=2). Since 3 is at index 2 in sorted array, we need 2 deletions.
Example 2 — No Solution
$
Input:
nums = [7,21,14], numsDivide = [5,10,15]
›
Output:
-1
💡 Note:
No element in nums can divide all elements in numsDivide. For example, 7 doesn't divide 5 (5÷7 has remainder), 14 doesn't divide 5, and 21 doesn't divide 5. Since no valid divisor exists, return -1.
Example 3 — First Element Works
$
Input:
nums = [1,2,3], numsDivide = [2,4,6]
›
Output:
0
💡 Note:
The smallest element 1 divides all elements in numsDivide (2÷1=2, 4÷1=4, 6÷1=6). Since 1 is already the smallest, no deletions needed.
Constraints
- 1 ≤ nums.length, numsDivide.length ≤ 105
- 1 ≤ nums[i], numsDivide[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
nums array to modify and numsDivide array as targets
2
Find Target
Calculate what the divisor needs to be (GCD of numsDivide)
3
Count Deletions
Sort nums and find first valid element
Key Takeaway
🎯 Key Insight: Use GCD to determine the target divisor - any element that divides all numbers must also divide their GCD
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code