Minimum Operations to Make Array Sum Divisible by K - Problem

You're given an integer array nums and an integer k. Your goal is to make the sum of all elements in the array divisible by k using the minimum number of operations.

Operation: Select any index i and replace nums[i] with nums[i] - 1 (decrease by 1).

What's the minimum number of operations needed?

Example: If nums = [1, 2, 3] and k = 3, the sum is 6, which is already divisible by 3, so we need 0 operations. But if nums = [1, 2, 4] and k = 3, the sum is 7. We need to reduce it by 1 to make it 6 (divisible by 3), so the answer is 1.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 2, 3], k = 3
โ€บ Output: 0
๐Ÿ’ก Note: Sum = 6, which is already divisible by 3 (6 % 3 = 0), so no operations needed.
example_2.py โ€” Single Operation
$ Input: nums = [1, 2, 4], k = 3
โ€บ Output: 1
๐Ÿ’ก Note: Sum = 7, and 7 % 3 = 1. We need 1 operation to make it 6, which is divisible by 3.
example_3.py โ€” Multiple Operations
$ Input: nums = [5, 6, 7], k = 4
โ€บ Output: 2
๐Ÿ’ก Note: Sum = 18, and 18 % 4 = 2. We need 2 operations to make it 16, which is divisible by 4.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 106
  • 1 โ‰ค k โ‰ค 106
  • Important: We can only decrease elements, never increase them

Visualization

Tap to expand
Number Line Visualization036912Multiples of k=37 (current sum)Need to move 1 step left7 - 6 = 1 operation7 % 3 = 1 โœ“General FormulaOperations needed = current_sum % kThis gives us the distance to the nearest smaller multiple!
Understanding the Visualization
1
Find Current Position
Calculate sum of array elements
2
Find Target
Locate nearest smaller multiple of k
3
Calculate Gap
The gap is sum % k operations
4
Minimize Steps
Each operation reduces sum by 1
Key Takeaway
๐ŸŽฏ Key Insight: The remainder when dividing the sum by k tells us exactly how many steps we need to 'walk backwards' to reach divisibility!
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
28.4K Views
Medium Frequency
~8 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