Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Number Theory
Minimum Operations To Make Array Sum Divisible By K

Find the minimum number of element adjustments needed so the total sum becomes divisible by k.

Acceptance 0%
Problem Statement

Problem

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

In one operation, you may change the value of a single array element by 1 in either direction. Your goal is to make the sum of the array divisible by k using the fewest operations possible.

Return the minimum number of operations required.

Intuition

Only the remainder of the total sum modulo k matters. Each +1 or -1 operation changes the sum by exactly one, so the answer is determined by how far the current sum is from the nearest multiple of k.

Input Format

  • nums: an integer array
  • k: a positive integer

You may assume the array can be modified by incrementing or decrementing individual elements by 1 per operation.

Output Format

Return the minimum number of +1/-1 operations needed so that the sum of nums is divisible by k.

Constraints

  • 1 <= nums.length
  • k > 0
  • Values fit in standard integer ranges for interview use
  • Each operation changes one element by exactly 1
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [3, 1, 4, 2], k = 6

Output

0

Explanation

The sum is 10, and 10 mod 6 = 4. Since we can change one element by 2, or equivalently adjust the total by the needed amount, the minimum operations are determined by the remainder. In this illustrative version, if the task is to make the sum divisible by 6 by unit operations, the cheapest total adjustment is 2.

Example 2

Input

nums = [1, 2, 3], k = 4

Output

2

Explanation

The sum is 6, and 6 mod 4 = 2. Two -1 operations (for example, changing 3 -> 1) reduce the sum by 2, making it divisible by 4.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.