Minimum Deletions to Make Array Divisible - Problem

You are given two arrays: nums and numsDivide. Your goal is to find the minimum number of deletions from nums such that the smallest remaining element in nums can divide all elements in numsDivide.

Key Insight: An integer x divides y if y % x == 0 (no remainder).

For example, if nums = [2,3,2,4,3] and numsDivide = [9,6,9,3,15], we need to delete elements from nums until the smallest element can divide all numbers in numsDivide. The number 3 divides all elements in numsDivide, so we delete elements to make 3 the smallest.

Return -1 if it's impossible to achieve this goal.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]
โ€บ Output: 2
๐Ÿ’ก Note: We need to delete 2 elements from nums. The GCD of numsDivide is 3, and the smallest element in nums that divides 3 is 3 itself. We need to delete the two 2's to make 3 the smallest element.
example_2.py โ€” Impossible Case
$ Input: nums = [4,3,6,8], numsDivide = [2,9,15,6]
โ€บ Output: -1
๐Ÿ’ก Note: The GCD of numsDivide is 1, but none of the elements 4,3,6,8 can divide 1 (only 1 itself can divide 1). Therefore, it's impossible.
example_3.py โ€” No Deletions Needed
$ Input: nums = [1,2,3], numsDivide = [2,4,6]
โ€บ Output: 0
๐Ÿ’ก Note: The smallest element 1 can divide all elements in numsDivide [2,4,6], so no deletions are needed.

Constraints

  • 1 โ‰ค nums.length, numsDivide.length โ‰ค 105
  • 1 โ‰ค nums[i], numsDivide[i] โ‰ค 109
  • All elements in arrays are positive integers

Visualization

Tap to expand
The Universal Key ProblemKeys (nums): [2,3,2,4,3] โ†’ Locks (numsDivide): [9,6,9,3,15]2329615Step 1: Find Master Pattern (GCD)GCD(9,6,9,3,15) = 3Any key must have pattern that divides 3Step 2: Sort Keys and Find First MatchSorted: [2,2,3,3,4] โ†’ First key that divides 3 is at index 2Delete 2 keys before it: Answer = 2๐ŸŽฏ Key Insight: Use GCD to avoid checking every combination!Time: O(n log n) instead of O(nยฒm)
Understanding the Visualization
1
Find Master Pattern
Calculate GCD of all locks - this tells us what pattern any key must have
2
Sort Keys
Arrange keys from smallest to largest
3
Find First Match
The first key that matches the master pattern is our answer
Key Takeaway
๐ŸŽฏ Key Insight: The mathematical property that any common divisor must divide the GCD allows us to reduce the search space dramatically, turning a complex combinatorial problem into a simple sorting and searching problem.
Asked in
Google 42 Amazon 35 Meta 28 Microsoft 22
52.0K Views
Medium Frequency
~25 min Avg. Time
1.8K 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