Find Minimum Operations to Make All Elements Divisible by Three - Problem
You are given an integer array nums. Your goal is to make all elements in the array divisible by 3 using the minimum number of operations.
In one operation, you can either:
- Add 1 to any element
- Subtract 1 from any element
Return the minimum number of operations needed to make all elements divisible by 3.
Example: If you have [1, 2, 4], you need 1 operation for each element: change 1→0 or 1→3, change 2→3, and change 4→3. Total: 3 operations.
Input & Output
example_1.py — Basic Case
$
Input:
[3, 1, 4]
›
Output:
2
💡 Note:
3 is already divisible by 3 (0 operations). 1 needs 1 operation (1→0 or 1→3). 4 needs 1 operation (4→3). Total: 0 + 1 + 1 = 2 operations.
example_2.py — All Divisible
$
Input:
[0, 3, 6, 9]
›
Output:
0
💡 Note:
All numbers are already divisible by 3, so no operations are needed.
example_3.py — Mixed Cases
$
Input:
[1, 2, 4, 5]
›
Output:
4
💡 Note:
1 % 3 = 1 (1 op), 2 % 3 = 2 (1 op), 4 % 3 = 1 (1 op), 5 % 3 = 2 (1 op). Total: 4 operations.
Constraints
- 1 ≤ nums.length ≤ 104
- 0 ≤ nums[i] ≤ 104
- Each operation changes an element by exactly ±1
Visualization
Tap to expand
Understanding the Visualization
1
Identify Problem
Each clock shows a wrong time, we need to fix them with minimum adjustments
2
Find Closest Target
For each clock, find the nearest 'good' position (divisible by 3)
3
Calculate Moves
Count minimum moves needed - never more than 1 move per clock
4
Sum Total
Add up all the individual moves to get the total operations
Key Takeaway
🎯 Key Insight: The minimum operations for any number is simply whether its remainder when divided by 3 is zero (0 ops) or non-zero (1 op).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code