Make Sum Divisible by P - Problem

You're given an array of positive integers nums and need to make the sum of the entire array divisible by a positive integer p. The twist? You can only achieve this by removing the smallest possible contiguous subarray.

Think of it as a precision surgery - you want to remove the minimal amount of elements while achieving your goal. The subarray you remove can be empty (if the sum is already divisible), but you cannot remove the entire array.

Your mission: Find the length of the smallest subarray that needs to be removed to make the remaining sum divisible by p. If it's impossible to achieve this goal, return -1.

Example: For nums = [3,1,4,2], p = 6, the total sum is 10. We need to remove a subarray with sum โ‰ก 4 (mod 6). The subarray [4] has sum 4, so removing it leaves sum 6, which is divisible by 6. Answer: 1.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [3,1,4,2], p = 6
โ€บ Output: 1
๐Ÿ’ก Note: Total sum is 10. We need 10 % 6 = 4 remainder gone. Subarray [4] has sum 4, removing it leaves sum 6 which is divisible by 6.
example_2.py โ€” Already Divisible
$ Input: nums = [6,3,5,2], p = 9
โ€บ Output: 2
๐Ÿ’ก Note: Total sum is 16. We need 16 % 9 = 7 remainder gone. Subarray [5,2] has sum 7, removing it leaves sum 9 which is divisible by 9.
example_3.py โ€” 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.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค p โ‰ค 109
  • Important: Cannot remove the entire array

Visualization

Tap to expand
Modular Arithmetic VisualizationRemainder Circle (mod 6)012345Key InsightWe need to find a subarray whose sum โ‰ก 4 (mod 6)Using prefix sums: if prefix[j] - prefix[i] โ‰ก 4 (mod 6)then prefix[j] โ‰ก (prefix[i] + 4) (mod 6)Target: 4
Understanding the Visualization
1
Calculate Target
Find what remainder we need to eliminate: total_sum % p
2
Track Prefix Patterns
As we build prefix sums, track remainder patterns in hash map
3
Find Completion Points
When current_remainder - target_remainder matches a previous remainder, we found our subarray
4
Optimize Length
Keep track of the shortest valid subarray found
Key Takeaway
๐ŸŽฏ Key Insight: By storing prefix sum remainders in a hash map, we can instantly find if there's a previous position that creates the exact subarray sum we need to remove!
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
28.4K Views
Medium Frequency
~25 min Avg. Time
876 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