Back to posts

LeetCode Challenge Day 68 β€” 3190. Find Minimum Operations to Make All Elements Divisible by Three

Nitin Ahirwal / November 22, 2025

LeetCode ChallengeDay 68MathGreedyJavaScriptEasy

Hey folks πŸ‘‹

This is Day 68 of my LeetCode streak πŸš€
Today’s problem is 3190 β€” Find Minimum Operations to Make All Elements Divisible by Three.

Given an array nums, in one operation we can add or subtract 1 from an element.
Our task is to make all elements divisible by 3 with the minimum number of operations.


πŸ’‘ Intuition

Every number is at most one step away from a multiple of 3:

| num % 3 | Action | Cost | |----------|--------|------| | 0 | Already divisible by 3 | 0 | | 1 | Do num - 1 | 1 | | 2 | Do num + 1 | 1 |

So every element that is not divisible by 3 requires exactly one operation.


πŸ“Œ Approach

  1. Loop through the array.
  2. If a number is divisible by 3 β†’ no change needed.
  3. Otherwise β†’ increment the operation counter.
  4. Return the counter.

Because each non-divisible number costs exactly one operation,
the result is just the number of elements where num % 3 !== 0.


πŸ“ˆ Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

πŸ§‘β€πŸ’» Code (JavaScript)

/**
 * @param {number[]} nums
 * @return {number}
 */
var minimumOperations = function(nums) {
    let ops = 0;
    
    for (const x of nums) {
        if (x % 3 !== 0) {
            ops += 1;
        }
    }
    
    return ops;
};

🧠 Reflection

Not every problem needs simulation β€” sometimes a mathematical observation gives the most optimal solution.
Realizing that every number is only one step away from being divisible by 3 simplifies the challenge drastically.

See you tomorrow for Day 69! πŸš€
Happy Coding πŸ‘¨β€πŸ’»βœ¨