Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created November 22, 2025 23:53
Show Gist options
  • Select an option

  • Save Ifihan/dc9706d187a377f64931c33ec127541e to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/dc9706d187a377f64931c33ec127541e to your computer and use it in GitHub Desktop.
Find Minimum Operations to Make All Elements Divisible by Three

Question

Approach

For each number, I only care about its remainder mod 3:

  • If num % 3 == 0, cost = 0 (already divisible).
  • If num % 3 == 1, I can subtract 1 → cost = 1.
  • If num % 3 == 2, I can add 1 → cost = 1.

Since adding/subtracting 1 always brings the number directly to a multiple of 3, every non-divisible number costs exactly 1 operation. So I simply count how many numbers have remainder 1 or 2.

Implementation

class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        ans = 0
        for x in nums:
            if x % 3 != 0:
                ans += 1
        return ans

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment