Leetcode #2344: Minimum Deletions to Make Array Divisible
In this guide, we solve Leetcode #2344 Minimum Deletions to Make Array Divisible in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Number Theory, Sorting, Heap (Priority Queue)
Intuition
We need to repeatedly access the smallest or largest element as the input changes.
A heap provides fast insertions and removals while keeping order.
Approach
Push candidates into the heap as you scan, and pop when you need the best element.
Keep the heap size bounded if the problem requires a top-k structure.
Steps:
- Push candidates into a heap.
- Pop the best candidate when needed.
- Maintain heap size or invariants.
Example
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.
Python Solution
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
Complexity
The time complexity is O(n log n). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.