Make Sum Divisible by P - Problem

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.

Input & Output

Example 1 — Basic Removal
$ Input: nums = [3,1,4,2], p = 6
Output: 1
💡 Note: Total sum is 10. We need sum divisible by 6. Remove subarray [4] (length 1) to get [3,1,2] with sum 6, which is divisible by 6.
Example 2 — No Removal Needed
$ Input: nums = [6,3,5,2], p = 9
Output: 2
💡 Note: Total sum is 16. Remove subarray [5,2] (length 2) to get [6,3] with sum 9, which is divisible by 9.
Example 3 — Impossible Case
$ Input: nums = [1,2,3], p = 3
Output: 0
💡 Note: Total sum is 6, which is already divisible by 3. No removal needed, return 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ p ≤ 109

Visualization

Tap to expand
Make Sum Divisible by P: Remove Minimum Subarray3142Original sum: 3+1+4+2 = 10, remainder: 10%6 = 4Remove this elementAfter removal: [3,1,2], sum = 66 % 6 = 0 ✓ (divisible by 6)Output: 1 (minimum length to remove)
Understanding the Visualization
1
Input
Array [3,1,4,2] and divisor p=6
2
Process
Find shortest subarray with remainder 4
3
Output
Remove 1 element to make remaining sum divisible
Key Takeaway
🎯 Key Insight: Use prefix sums and hash map to efficiently find the shortest subarray whose remainder matches the total remainder
Asked in
Facebook 15 Google 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen