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.
1#include <vector>
2#include <unordered_map>
3#include <numeric>
4using namespace std;
5
6int minSubarray(vector<int>& nums, int p) {
7 int total_mod = accumulate(nums.begin(), nums.end(), 0) % p;
8 if (total_mod == 0) return 0;
9 unordered_map<int, int> prefix_map;
10 prefix_map[0] = -1;
11 int prefix_sum = 0, min_len = nums.size();
12 for (int i = 0; i < nums.size(); ++i) {
13 prefix_sum = (prefix_sum + nums[i]) % p;
14 int target = (prefix_sum - total_mod + p) % p;
15 if (prefix_map.find(target) != prefix_map.end()) {
16 min_len = min(min_len, i - prefix_map[target]);
17 }
18 prefix_map[prefix_sum] = i;
19 }
20 return min_len == nums.size() ? -1 : min_len;
21}This C++ solution uses the same logic as the Python solution, with an unordered_map to store prefix sums and find the minimum subarray length to remove for the desired remainder. Aggregating the numbers, modular arithmetic is used to achieve the desired check.
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.
1import java.util.*;
2
3Watch 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.
The Java solution uses a HashMap to keep track of prefix sums as keys, linked to their indexes. The final loop computes prefix sums iteratively and checks for the desired remainder, computing the minimal subarray, if applicable.