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 INPUT nums array: 3 i=0 1 i=1 4 i=2 2 i=3 Parameters: nums = [3, 1, 4, 2] p = 6 Total Sum: 3+1+4+2 = 10, 10%6 = 4 Need remainder = 4 ALGORITHM STEPS 1 Calculate Target target = sum % p = 4 2 Init HashMap Store prefix sum % p 3 Iterate Array Find (cur-target+p)%p 4 Track Min Length Update shortest subarray HashMap (prefix%p : index) { 0: -1 } init { 0: -1, 3: 0 } i=0 { 0: -1, 3: 0, 4: 1 } i=1 cur=4, need=0 in map! Found: i=2, map[0]=-1 FINAL RESULT Remove subarray [4]: 3 1 4 2 REMOVED Remaining Elements: [3, 1, 2] sum = 6 6 % 6 = 0 -- OK OUTPUT 1 Minimum subarray length to remove is 1 Key Insight: Use prefix sums with hash map to find subarrays with sum % p = target. If current prefix % p = cur, we need previous prefix where (cur - target + p) % p exists. This gives O(n) time complexity instead of O(n^2) brute force approach. TutorialsPoint - Make Sum Divisible by P | Hash Map Approach
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