#3512
Minimum Operations to Make Array Sum Divisible by K
EasyArrayMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of reducing elements one by one, we can calculate how much we need to reduce the total sum to make it divisible by k, which is more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the sum of the array.
- 2Step 2: Find the remainder when the sum is divided by k.
- 3Step 3: The minimum operations needed is equal to the remainder, since we can reduce any element directly to achieve divisibility.
solution.py4 lines
1def min_operations(nums, k):
2 total = sum(nums)
3 remainder = total % k
4 return remainderℹ
Complexity note: The sum calculation is O(n), and we only need a constant amount of space.
- 1The sum's remainder when divided by k directly gives the number of operations needed.
- 2Reducing elements one by one is inefficient compared to calculating the total sum's remainder.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.