Minimum Operations to Make Array Sum Divisible by K (LeetCode 3512): Solution and Explanation
Each operation subtracts 1 from one element. Return the fewest operations that make the array sum a multiple of k.
Intuition
An operation lowers one element by 1, which lowers the whole sum by 1. Which element you pick never matters, so the problem is really about a single number: the sum.
Operations only move the sum down. The closest multiple of k you can reach going down is the largest multiple at or below the sum, which is sum - sum % k.
Getting there takes exactly sum % k steps, and no shorter path exists because each step moves the sum by only 1.
Approach: Sum modulo k
- Add up every element into
total. - Return
total % k.
Step-by-step example
nums = [3,9,7], k = 5
- total = 3 + 9 + 7 = 19.
- 19 = 3 x 5 + 4, so the sum sits 4 above the multiple 15.
- Four decrements take the sum from 19 to 15.
- Return 4.
Code: Python, Java, C++
1class Solution:
2 def minOperations(self, nums: List[int], k: int) -> int:
3 total = 0
4 for x in nums:
5 total += x
6 return total % k1class Solution {
2 public int minOperations(int[] nums, int k) {
3 int total = 0;
4 for (int x : nums) {
5 total += x;
6 }
7 return total % k;
8 }
9}1class Solution {
2public:
3 int minOperations(vector<int>& nums, int k) {
4 int total = 0;
5 for (int x : nums) {
6 total += x;
7 }
8 return total % k;
9 }
10};Time and space complexity
O(n)
One pass to add up the elements, then a single modulo.
O(1)
Only the running total is stored.
Other approaches
Simulate decrements (time O(n + k), space O(1))
Subtract 1 from the sum until it is divisible by k, counting steps. It gives the same answer with up to k - 1 extra iterations.
Running remainder (time O(n), space O(1))
Keep total = (total + x) % k while scanning. Useful in languages where the sum could overflow, though here it stays below 10^6.
Common mistakes
- Thinking the answer depends on which elements you decrement. Only the sum changes in a way that matters.
- Returning
k - total % k, which would be the cost of increasing the sum. Operations only decrease. - Simulating one decrement at a time on the array. It works but hides the one line answer and adds needless loops.
Frequently asked questions
Why is the answer simply sum % k?
Each operation lowers the sum by exactly 1, and the nearest reachable multiple of k is sum - sum % k. That is sum % k steps away.
Can the answer be 0?
Yes. If the sum is already a multiple of k no operation is needed.
Does the choice of index ever matter?
No. Every operation has the same effect on the sum, so any sequence of sum % k decrements works.