Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a contiguous block of elements in the array.
Example 1:
Input: nums = [3,1,4,2], p = 6 Output: 1 Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
Example 2:
Input: nums = [6,3,5,2], p = 9 Output: 2 Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.
Example 3:
Input: nums = [1,2,3], p = 3 Output: 0 Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1091 <= p <= 109In #1590 Make Sum Divisible by P, the goal is to remove the smallest subarray so that the remaining array sum becomes divisible by p. A key observation is that if the total sum has remainder r = totalSum % p, we need to remove a subarray whose sum also leaves remainder r modulo p.
To efficiently find such a subarray, we use a prefix sum with modulo technique combined with a hash table. While iterating through the array, maintain the current prefix remainder prefix % p. The idea is to check whether a previous prefix remainder exists that would make the removed subarray’s sum congruent to r modulo p. A hash map helps store the latest index of each remainder for quick lookup.
This approach avoids checking all subarrays and reduces the problem to a single pass through the array. The method runs in O(n) time with O(n) additional space for the hash map.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Prefix Sum with Hash Map | O(n) | O(n) |
NeetCodeIO
Use these hints if you're stuck. Try solving on your own first.
Use prefix sums to calculate the subarray sums.
Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k?
Use a map to keep track of the rightmost index for every prefix sum % p.
This approach involves first calculating the remainder of the sum of the given array with respect to p. By maintaining a prefix sum and using the properties of modular arithmetic, we can determine the shortest subarray whose removal results in a remainder of zero.
Time Complexity: O(n), where n is the length of nums.
Space Complexity: O(n), for storing prefix sums in the hashmap.
1def min_subarray(nums, p):
2 total_mod = sum(nums) % p
3 if total_mod == 0:
4 return 0
5 prefix_sum = 0
6 prefix_map = {0: -1}
7 min_len = len(nums)
8 for i, num in enumerate(nums):
9 prefix_sum = (prefix_sum + num) % p
10 target = (prefix_sum - total_mod) % p
11 if target in prefix_map:
12 min_len = min(min_len, i - prefix_map[target])
13 prefix_map[prefix_sum] = i
14 return min_len if min_len != len(nums) else -1This implementation calculates the prefix sum and stores remainders in a hashmap. By checking if the target remainder exists in the hashmap, we find the minimal subarray that aligns with our requirement. We update the hashmap with current prefix sums iteratively.
This approach makes use of a sliding window or two-pointer technique to identify the minimal subarray which upon removal makes the sum of the remaining elements divisible by p.
Time Complexity: O(n), where n is the length of nums.
Space Complexity: O(n), for maintaining the hashmap.
1function minSubarray(nums, p) {
2 letWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Yes, problems involving prefix sums and hash maps are common in FAANG-style interviews. #1590 Make Sum Divisible by P tests modular arithmetic, array traversal, and hash-based optimization, which are key interview concepts.
Prefix sums allow us to compute subarray sums efficiently without recalculating values repeatedly. When combined with modulo operations, they help detect subarrays whose removal fixes the total remainder.
A hash map is the most useful data structure for this problem. It stores prefix sum remainders and their indices, allowing constant-time lookups to detect valid subarrays that satisfy the modulo condition.
The optimal approach uses prefix sums with modulo arithmetic and a hash map. By tracking prefix remainders, we can quickly identify the smallest subarray whose removal makes the total sum divisible by p in O(n) time.
This JavaScript implementation aligns with previous versions, utilizing an object to store prefix sums and applying similar logic to finalize the computation of the minimal subarray which satisfies the given condition.