Find Minimum Operations to Make All Elements Divisible by Three (LeetCode 3190): Solution and Explanation
You may add 1 to or subtract 1 from any element of nums, one unit per operation. Return the fewest operations that make every element divisible by 3.
Intuition
Operations on one element never affect another, so the answer is the sum of the cost for each element on its own.
For a single number x, the cost is its distance to the nearest multiple of 3. Multiples of 3 sit 3 apart on the number line, so between two consecutive multiples there are only two other integers, and each of them is right next to one of the multiples.
Concretely, if x % 3 == 1, subtracting 1 lands on a multiple. If x % 3 == 2, adding 1 does. If x % 3 == 0, nothing is needed. So every element costs either 0 or 1.
The answer is therefore just the number of elements that are not divisible by 3.
Approach: Count the non-multiples
- Set
ops = 0. - For each
xinnums, ifx % 3 != 0, add 1 toops. - Return
ops.
Step-by-step example
nums = [1,2,3,4]
- 1 % 3 = 1: step down to 0. ops = 1.
- 2 % 3 = 2: step up to 3. ops = 2.
- 3 % 3 = 0: already divisible. ops stays 2.
- 4 % 3 = 1: step down to 3. ops = 3.
- Return 3.
Code: Python, Java, C++
1class Solution:
2 def minimumOperations(self, nums: List[int]) -> int:
3 ops = 0
4 for x in nums:
5 if x % 3 != 0:
6 ops += 1
7 return ops1class Solution {
2 public int minimumOperations(int[] nums) {
3 int ops = 0;
4 for (int x : nums) {
5 if (x % 3 != 0) {
6 ops++;
7 }
8 }
9 return ops;
10 }
11}1class Solution {
2public:
3 int minimumOperations(vector<int>& nums) {
4 int ops = 0;
5 for (int x : nums) {
6 if (x % 3 != 0) {
7 ops++;
8 }
9 }
10 return ops;
11 }
12};Time and space complexity
O(n)
Each element is checked once with a single modulo.
O(1)
Only the counter is stored.
Other approaches
Distance to the nearest multiple (time O(n), space O(1))
Add min(x % 3, 3 - x % 3) for each element. It computes the same 0 or 1 explicitly and generalizes to any divisor k, where the cost would be min(x % k, k - x % k).
One-line count (time O(n), space O(1))
In Python, sum(x % 3 != 0 for x in nums) expresses the same count in a single expression.
Common mistakes
- Adding
x % 3as the cost. A remainder of 2 needs only one addition, not two subtractions. - Thinking the elements must all become the same multiple of 3. Each element only has to be divisible by 3 on its own.
- Trying a greedy or DP over the array. The elements are independent, so a plain count is optimal.
Frequently asked questions
Why is the cost for one element never more than 1?
Multiples of 3 are 3 apart, so every integer is either a multiple or directly next to one. Remainder 1 is one above a multiple and remainder 2 is one below the next.
Would the idea work for a divisor other than 3?
Yes, but the cost per element becomes min(x % k, k - x % k), which can be larger than 1 when k is 4 or more.
What is the time complexity?
O(n) time for one pass over the array and O(1) extra space.