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
Minimum Deletions to Make Array Divisible INPUT nums array: 2 3 2 4 6 7 4 numsDivide array: 9 3 12 6 Goal: Find min deletions so smallest in nums divides all of numsDivide Sorted nums: [2, 2, 3, 4, 4, 6, 7] ALGORITHM STEPS 1 Find GCD of numsDivide GCD(9,3,12,6) = 3 2 Sort nums ascending [2,2,3,4,4,6,7] 3 Check each element If GCD % element == 0 4 Count deletions Until valid found Checking (GCD=3): 2: 3%2=1 != 0 [X] 2: 3%2=1 != 0 [X] 3: 3%3=0 == 0 [OK] Found at index 2! FINAL RESULT Elements to delete: 2 2 Remaining array: 3 4 4 6 7 4 Smallest = 3 divides all! Output: 2 Verification: 9%3=0, 3%3=0 12%3=0, 6%3=0 [OK] Key Insight: For an element x to divide ALL elements in numsDivide, x must divide the GCD of numsDivide. Sort nums and find first element that divides GCD. Count of smaller elements = minimum deletions. Time: O(n log n + m log m) | Space: O(1) where n=len(nums), m=len(numsDivide) TutorialsPoint - Minimum Deletions to Make Array Divisible | Optimal Solution
Asked in
Google 15 Meta 8
21.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen