Leetcode 1590: Make Sum Divisible by P

grid47
grid47
Exploring patterns and algorithms
Jun 1, 2024 7 min read

Given an array of positive integers nums and an integer p, your task is to remove the smallest subarray (contiguous elements) such that the sum of the remaining elements is divisible by p. If it’s impossible, return -1. Note that the entire array cannot be removed.
Problem
Approach
Steps
Complexity
Input: The input consists of a positive integer array nums and an integer p. The length of nums is between 1 and 10^5, and each element of nums is between 1 and 10^9. The value of p is also between 1 and 10^9.
Example: Input: nums = [4, 2, 3, 5], p = 8
Constraints:
• 1 <= nums.length <= 10^5
• 1 <= nums[i] <= 10^9
• 1 <= p <= 10^9
Output: Return the length of the smallest subarray that you need to remove so that the sum of the remaining elements is divisible by p. If no such subarray exists, return -1.
Example: Output: 2
Constraints:
• If the whole array cannot be removed and no solution exists, return -1.
Goal: The goal is to find the smallest subarray that, when removed, ensures the sum of the remaining elements is divisible by p. This involves checking the remainders when elements are added up and removing the minimum contiguous subarray that achieves the result.
Steps:
• 1. Calculate the total sum of the array.
• 2. If the total sum is already divisible by p, no removal is needed, and the answer is 0.
• 3. Compute the remainder when the sum of the array is divided by p.
• 4. Traverse the array, maintaining a running sum modulo p, and check if a valid subarray exists whose removal makes the total sum divisible by p.
• 5. Keep track of the minimum length of such a subarray and return the result.
Goal: This problem has constraints on the size of the array and the values of the elements and p. The solution must be efficient to handle large inputs.
Steps:
• 1 <= nums.length <= 10^5
• 1 <= nums[i] <= 10^9
• 1 <= p <= 10^9
Assumptions:
• The array nums contains only positive integers.
• It's guaranteed that the array is non-empty and contains at least one element.
Input: Input: nums = [4, 2, 3, 5], p = 8
Explanation: The sum of the array is 14. To make it divisible by 8, we need to remove the subarray [2, 3] (which has sum 5). The remaining sum is 9, which is divisible by 8. Hence, the smallest subarray to remove is of length 2.

Input: Input: nums = [5, 5, 5, 5], p = 7
Explanation: The sum of the array is 20. We cannot remove any single element or any subarray to get a sum divisible by 7. Hence, the result is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus