#3190
Find Minimum Operations to Make All Elements Divisible by Three
EasyArrayMathMathArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that each number can be adjusted to the nearest multiple of 3 in at most one operation. By calculating the necessary adjustments directly, we can achieve the result more efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a counter for operations to 0.
- 2Step 2: For each element in the array, calculate the remainder when divided by 3.
- 3Step 3: If the remainder is not zero, add the minimum of the remainder and (3 - remainder) to the operations counter.
solution.py2 lines
1def min_operations(nums):
2 return sum(min(num % 3, 3 - (num % 3)) for num in nums)ℹ
Complexity note: The time complexity remains O(n) as we still iterate through the array once, and the space complexity is O(1) since we use a constant amount of extra space.
- 1Each number can be adjusted to a multiple of 3 in at most one operation.
- 2Understanding the modulo operation helps in determining the necessary adjustments.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.