Find Minimum Operations to Make All Elements Divisible by Three - Problem

You are given an integer array nums. In one operation, you can add or subtract 1 from any element of nums.

Return the minimum number of operations to make all elements of nums divisible by 3.

Input & Output

Example 1 — Mixed Numbers
$ Input: nums = [3,1,2,4,0]
Output: 3
💡 Note: 3 is divisible (0 ops), 1→0 (1 op), 2→3 (1 op), 4→3 (1 op), 0 is divisible (0 ops). Total: 3 operations
Example 2 — All Divisible
$ Input: nums = [0,3,6,9]
Output: 0
💡 Note: All numbers are already divisible by 3, so no operations needed
Example 3 — All Need Adjustment
$ Input: nums = [1,2,4,5]
Output: 4
💡 Note: 1→0 (1 op), 2→3 (1 op), 4→3 (1 op), 5→6 (1 op). Total: 4 operations

Constraints

  • 1 ≤ nums.length ≤ 50
  • 0 ≤ nums[i] ≤ 50

Visualization

Tap to expand
Make All Elements Divisible by 3Input Array:312403%3=01%3=12%3=24%3=10%3=00 ops1 op1 op1 op0 opsTotal Operations: 0 + 1 + 1 + 1 + 0Result: 3
Understanding the Visualization
1
Input Array
Array with mixed numbers
2
Calculate Operations
Check each number's distance to nearest multiple of 3
3
Sum Total
Return total operations needed
Key Takeaway
🎯 Key Insight: Any integer is at most 1 step away from a multiple of 3
Asked in
Google 15 Amazon 12
12.0K Views
Medium Frequency
~8 min Avg. Time
450 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