Problem Description
Given an array of positive integers, the goal is to remove the smallest possible subarray (which can be empty) such that the sum of the remaining elements is divisible by a given integer p. Removing the entire array is not allowed. If it’s impossible to achieve a sum divisible by p, return -1.
Key Insights
- Compute the total sum of the array and determine its remainder when divided by p.
- If the total sum is already divisible by p (remainder equals 0), no elements need to be removed.
- The problem can be reduced to finding a subarray whose sum has a remainder equal to the surplus (r) when the total sum is divided by p.
- Use prefix sums and take modulo p at each step. Store seen remainders and their indices in a hash map.
- For each prefix sum modulo value, checking for an earlier prefix sum with an appropriate modulo value facilitates identification of a subarray with the desired remainder.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array, since we iterate over the array once. Space Complexity: O(n), due to the hash map storing prefix modulo values and their indices.
Solution
The solution starts by calculating the remainder r when the total sum of the array is divided by p. If r is 0, the array’s sum is already divisible by p, so the answer is 0. Otherwise, we need to find the minimal contiguous subarray whose removal makes the remaining sum divisible by p.
To achieve this:
- Use a prefix sum and track its remainder modulo p.
- Maintain a hash map (or dictionary) to store the latest index for each prefix remainder.
- For each index, compute the current prefix sum modulo p. Then determine the target remainder by subtracting r (mod p) from the current prefix sum modulo p.
- If the target remainder exists in the hash map, update the minimum subarray length needed.
- Finally, if the minimum length equals the total array length (which means removing the whole array), return -1. Otherwise, return the minimum subarray length.