Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Number Theory
Find Minimum Operations To Make All Elements Divisible By Three

Given an array, find the minimum number of element changes needed so every value becomes divisible by 3.

Acceptance 0%
Problem Statement

Problem

You are given an integer array nums. In one operation, you may choose an element and change it by +1 or -1.

Return the minimum number of operations required so that every element in the array becomes divisible by 3.

Because each operation changes a value by exactly one, the cost to make a number divisible by 3 depends only on its remainder when divided by 3.

Clarification

  • You may apply operations to any elements, in any order.
  • The goal is to minimize the total number of +1/-1 steps across the entire array.

Input Format

  • A single integer array nums.

Output Format

  • Return an integer: the minimum total number of operations needed.

Constraints

  • 1 <= nums.length <= $10^{5}$
  • 0 <= nums[i] <= $10^{9}$

Notes

  • Numbers already divisible by 3 need no changes.
  • A number with remainder 1 can be fixed in one step.
  • A number with remainder 2 can also be fixed in one step by decreasing it by 1, or in two steps by increasing it to the next multiple of 3 depending on the allowed move strategy; choose the minimum per element.

Input Format

  • nums: integer array

Output Format

  • Return the minimum number of +1/-1 operations required so that all elements are divisible by 3.

Constraints

  • 1 <= nums.length <= $10^{5}$
  • 0 <= nums[i] <= $10^{9}$
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [3, 6, 1, 2]

Output

2

Explanation

3 and 6 are already divisible by 3. 1 needs one -1 operation, and 2 needs one -1 operation. Total = 2.

Example 2

Input

nums = [4, 7, 10]

Output

3

Explanation

Each value leaves remainder 1 when divided by 3, so each needs one operation to become divisible by 3. Total = 3.

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.