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
Minimum Operations for Divisibility by 3 INPUT nums = [3, 1, 2, 4, 0] 3 1 2 4 0 Remainders (num % 3): 0 1 2 1 0 r=0: OK r=1: -1 op r=2: +1 op Operations Needed: 0 1 1 1 0 Total: 0+1+1+1+0 = 3 ALGORITHM STEPS 1 Initialize counter ops = 0 2 Loop through array For each num in nums 3 Calculate remainder r = num % 3 4 Add min operations ops += min(r, 3-r) Why min(r, 3-r)? If r=0: min(0,3)=0 If r=1: min(1,2)=1 (sub 1) If r=2: min(2,1)=1 (add 1) Always 1 op max per element! FINAL RESULT After applying operations: 3 0 3 3 0 no op -1 +1 -1 no op OUTPUT 3 Verification: 3 % 3 = 0 OK 0 % 3 = 0 OK 3 % 3 = 0 OK 3 % 3 = 0 OK 0 % 3 = 0 OK Key Insight: For any number, to make it divisible by 3, we need at most 1 operation. If remainder is 1: subtract 1. If remainder is 2: add 1. This gives us min(r, 3-r) for each element. Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Find Minimum Operations to Make All Elements Divisible by Three | Optimal Solution
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