Make Sum Divisible by P Problem
Description
LeetCode Problem 1590.
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 <= 10^51 <= nums[i] <= 10^91 <= p <= 10^9
Solution
Approach: Prefix Sums Modulo p + Hash Map
Let k = sum(nums) % p. If k == 0, nothing has to be removed. Otherwise the removed subarray must have a sum that is k modulo p, and we want the shortest one.
With prefix sums, the sum of nums[j+1..i] is prefix[i] - prefix[j]. We need prefix[i] - prefix[j] ≡ k (mod p), that is prefix[j] ≡ prefix[i] - k (mod p). Walk through the array keeping the current prefix sum cur modulo p, and a map last from each residue to the latest index where it appeared (the latest one gives the shortest subarray). At index i, look up (cur - k) mod p; if it is in the map at index j, the subarray of length i - j is a candidate. The map starts with 0 -> -1 for the empty prefix.
Two details:
- Removing the whole array is not allowed. That candidate has length
n, so if the best length is stilln, return-1. - Values and
pare up to10^9, so a running sum of two of them can overflow a 32-bit integer; reduce with 64-bit arithmetic. In languages where%can be negative, addpbefore taking% p.
Complexity: O(n) time and O(n) extra space for the map.
class Solution:
def minSubarray(self, nums: List[int], p: int) -> int:
k = sum(nums) % p # the removed subarray must have sum ≡ k (mod p)
if k == 0:
return 0
last = {0: -1} # prefix sum mod p -> last index where it occurred
cur = 0
n = len(nums)
ans = n
for i, x in enumerate(nums):
cur = (cur + x) % p
target = (cur - k) % p
if target in last:
ans = min(ans, i - last[target])
last[cur] = i
return -1 if ans == n else ans # removing the whole array is not allowed