#2344

Minimum Deletions to Make Array Divisible

Hard
ArrayMathSortingHeap (Priority Queue)Number TheoryMath (GCD, divisibility)Sorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

Instead of checking each element in nums, we can find the GCD of numsDivide. The smallest element in nums that divides this GCD will also divide all elements in numsDivide. This reduces our checks significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the GCD of all elements in numsDivide.
  2. 2Step 2: Sort the nums array.
  3. 3Step 3: Find the smallest element in nums that divides the GCD.
  4. 4Step 4: Return the number of deletions needed to remove elements smaller than this smallest divisor.
solution.py14 lines
1# Full working Python code
2import math
3from functools import reduce
4
5def gcd(a, b):
6    return math.gcd(a, b)
7
8def min_deletions_optimal(nums, numsDivide):
9    gcd_value = reduce(gcd, numsDivide)
10    nums.sort()
11    for i in range(len(nums)):
12        if gcd_value % nums[i] == 0:
13            return i
14    return -1

Complexity note: The sorting step dominates the complexity, while calculating the GCD is linear with respect to the size of numsDivide.

  • 1Finding the GCD of numsDivide helps in narrowing down the candidates for the smallest divisor.
  • 2Sorting nums allows us to efficiently find the smallest element that divides the GCD.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.