The Make Sum Divisible by P problem provides an array of positive integers and an integer p. Your objective is to remove the shortest possible contiguous subarray such that the sum of the remaining elements in the array is strictly divisible by p. If it's impossible, return -1. You cannot remove the entire array.
This is an advanced modular arithmetic and Hash Table problem. It is asked by top-tier companies to evaluate your mathematical reasoning. Instead of asking you to find a subarray that sums to X, it asks you to find a subarray to remove so the remainder is divisible. This tests your ability to invert a problem mathematically using the Prefix Sum modulo properties.
This problem leverages Prefix Sums and a Hash Map with modular arithmetic.
p. Let this be rem. If rem == 0, return 0 (no removal needed).p is exactly rem.p. We use a Hash Map to store the most recent index of each prefix sum modulo.(current_prefix_sum_mod - rem + p) % p. The distance between the current index and that previous index gives the length of the subarray to remove.Array [3, 1, 4, 2], p = 6.
Total sum = 10. 10 % 6 = 4. So rem = 4. We must remove a subarray that sums to 4 (mod 6).
Iterate and track prefix mod:
{0: -1}.3 % 6 = 3. We need (3 - 4 + 6) % 6 = 5. Not in map. Map {..., 3: 0}.4 % 6 = 4. We need (4 - 4 + 6) % 6 = 0. It IS in the map at -1! Length to remove = 1 - (-1) = 2. Subarray is [3, 1].8 % 6 = 2. We need (2 - 4 + 6) % 6 = 4. It IS in the map at 1! Length to remove = 2 - 1 = 1. Subarray is [4].
Minimum length found is 1 (removing just the 4 leaves 3+1+2=6, divisible by 6).The most common mistake is messing up the modulo math for negative numbers. In many programming languages (like Java and C++), a % b can be negative if a is negative. You must use the formula (current_mod - rem + p) % p to ensure the target you are looking for in the Hash Map is strictly positive. Another error is forgetting to prevent the removal of the entire array.
For the Make Sum Divisible by P coding problem, drill the relationship between prefix sums and targets. If you need a subarray sum equal to target, you look for current_sum - target in your map. If you need it modulo p, you look for (current_mod - target_mod + p) % p. This exact modulo formula is a recurring hero in advanced array manipulation interviews.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count of Interesting Subarrays | Medium | Solve | |
| Maximum Size Subarray Sum Equals k | Medium | Solve | |
| Subarray Sums Divisible by K | Medium | Solve | |
| Maximum Subarray Sum With Length Divisible by K | Medium | Solve | |
| Stable Subarrays With Equal Boundary and Interior Sum | Medium | Solve |