Minimum Operations to Make Array Sum Divisible by K - Problem

You are given an integer array nums and an integer k.

You can perform the following operation any number of times:

  • Select an index i and replace nums[i] with nums[i] - 1

Return the minimum number of operations required to make the sum of the array divisible by k.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,1,4,2], k = 6
Output: 4
💡 Note: Sum = 3+1+4+2 = 10. Since 10 % 6 = 4, we need 4 operations to reduce the sum by 4 and make it divisible by 6.
Example 2 — Already Divisible
$ Input: nums = [2,4], k = 3
Output: 0
💡 Note: Sum = 2+4 = 6. Since 6 % 3 = 0, the sum is already divisible by 3, so 0 operations needed.
Example 3 — Single Element
$ Input: nums = [5], k = 3
Output: 2
💡 Note: Sum = 5. Since 5 % 3 = 2, we need 2 operations to reduce 5 to 3, making it divisible by 3.

Constraints

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

Visualization

Tap to expand
Min Operations: Array Sum Divisible by K INPUT nums array: 3 i=0 1 i=1 4 i=2 2 i=3 Sum = 3 + 1 + 4 + 2 Sum = 10 Divisor: k = 6 Need: sum % k == 0 ALGORITHM STEPS 1 Calculate Sum sum = 3+1+4+2 = 10 2 Find Remainder remainder = sum % k 10 % 6 = 4 remainder = 4 3 Operations Needed ops = remainder 4 Result Reduce sum by 4 New sum: 10 - 4 = 6 6 % 6 = 0 [OK] FINAL RESULT Original sum: 10 Target: divisible by 6 Operations Breakdown Sum = 10 10 % 6 = 4 Need 4 decrements 10 - 4 = 6 (div by 6) Minimum Operations: 4 [OK] Verified! Key Insight: The minimum operations equals sum % k. Since each operation decreases sum by 1, we need exactly (sum mod k) operations to make the sum divisible by k. Formula: min_ops = sum(nums) % k = 10 % 6 = 4 TutorialsPoint - Minimum Operations to Make Array Sum Divisible by K | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.3K Views
Medium Frequency
~8 min Avg. Time
856 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