Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum Deletions to Make Array Divisible

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2344" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 that an integer x divides y if y % x == 0. Example 1: 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. Example 2: Input: nums = [4,3,6], numsDivide = [8,2,6,10] Output: -1 Explanation: We want the smallest element in nums to divide all the elements of numsDivide. There is no way to delete elements from nums to allow this. Constraints: 1 <= nums.length, numsDivide.length <= 105 1 <= nums[i], numsDivide[i] <= 109

Explanation

Here's the solution:

  • Find the greatest common divisor (GCD) of all numbers in numsDivide.
  • Sort the nums array. Iterate through the sorted nums array, and for each number, check if it divides the GCD calculated in the previous step. If it does, return the index of that number, as it represents the minimum number of deletions required to make it the smallest element.
  • If no number in nums divides the GCD, return -1.

  • Runtime complexity: O(n log n + m log m + n log GCD), where n is the length of nums and m is the length of numsDivide. Storage complexity: O(1).

Code

    import math

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def minOperations(nums, numsDivide):
    gcd_val = numsDivide[0]
    for i in range(1, len(numsDivide)):
        gcd_val = gcd(gcd_val, numsDivide[i])

    nums.sort()
    for i in range(len(nums)):
        if gcd_val % nums[i] == 0:
            return i

    return -1

More from this blog

C

Chatmagic blog

2894 posts