Minimum Deletions to Make Array Divisible — LeetCode 2344 Python Solution

HardArrayMathNumber TheorySortingHeap (Priority Queue)
Problem
#2344
Reading time
2 min

The problem

You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.

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.

Python solution

Python
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

MeasureComplexity
TimeO(n log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2344. Minimum Deletions to Make Array Divisible is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2344. Minimum Deletions to Make Array Divisible?
LeetCode 2344. Minimum Deletions to Make Array Divisible is rated Hard on LeetCode.
What is the time complexity of LeetCode 2344. Minimum Deletions to Make Array Divisible?
The Python solution on this page runs in O(n log n).
What is the space complexity of LeetCode 2344. Minimum Deletions to Make Array Divisible?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2344. Minimum Deletions to Make Array Divisible cover?
LeetCode 2344. Minimum Deletions to Make Array Divisible is tagged Array, Math, Number Theory, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview