|
| 1 | +# [Problem 3190: Find Minimum Operations to Make All Elements Divisible by Three](https://leetcode.com/problems/find-minimum-operations-to-make-all-elements-divisible-by-three/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +We only care about each number modulo 3. For a number x, let r = x % 3: |
| 5 | +- If r == 0, it's already divisible by 3 (cost 0). |
| 6 | +- If r == 1, we can subtract 1 (cost 1) or add 2 (cost 2) — best is 1. |
| 7 | +- If r == 2, we can add 1 (cost 1) or subtract 2 (cost 2) — best is 1. |
| 8 | + |
| 9 | +So each element with remainder 1 or 2 costs exactly 1 operation. That suggests the answer is simply the count of elements with remainder != 0. I briefly wondered if operations could be shared or paired to reduce cost, but operations act on single elements independently (add/subtract 1 to any element), so there's no sharing advantage. |
| 10 | + |
| 11 | +## Refining the problem, round 2 thoughts |
| 12 | +- Edge cases: small arrays, all already divisible by 3 -> answer 0. Works fine. |
| 13 | +- Alternative expression: sum(min(r, 3-r) for each remainder r) which reduces here to counting nonzero remainders since min(1,2)=1 and min(2,1)=1. |
| 14 | +- Time complexity: O(n) where n = len(nums). |
| 15 | +- Space complexity: O(1) extra (ignoring input), only a counter required. |
| 16 | +- Implementation detail: use generator expression to count nums with x % 3 != 0 for succinctness. |
| 17 | + |
| 18 | +## Attempted solution(s) |
| 19 | +```python |
| 20 | +from typing import List |
| 21 | + |
| 22 | +class Solution: |
| 23 | + def minimumOperations(self, nums: List[int]) -> int: |
| 24 | + # Each element with remainder 1 or 2 needs exactly 1 operation to become divisible by 3. |
| 25 | + return sum(1 for x in nums if x % 3 != 0) |
| 26 | +``` |
| 27 | +- Notes: |
| 28 | + - Approach: Count how many elements have remainder 1 or 2 modulo 3. Each such element requires one +1 or -1 operation. |
| 29 | + - Time complexity: O(n), single pass over the array. |
| 30 | + - Space complexity: O(1) extra (generator uses constant extra memory). |
0 commit comments