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
🕐 Clock Repair Shop - Fix Times Divisible by 3Clock 1Shows: 1 min01369Need: 1→0 or 1→3Operations: 1Clock 2Shows: 2 min01369Need: 2→3Operations: 1Clock 3Shows: 3 min01369Already perfect!Operations: 0🔧 Repair Strategy1. Check each clock's current position (remainder when ÷ 3)2. If remainder = 0: Clock is perfect, no repairs needed3. If remainder = 1 or 2: Move hand by 1 position (1 operation)Total Repairs: 1 + 1 + 0 = 2 operations
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).
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
26.8K 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