Find Minimum Operations to Make All Elements Divisible by Three Problem
#3190
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3190.
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.
Example 1:
Input: nums = [1,2,3,4]
Output: 3
Explanation:
All array elements can be made divisible by 3 using 3 operations:
- Subtract 1 from 1.
- Add 1 to 2.
- Subtract 1 from 4.
Example 2:
Input: nums = [3,6,9]
Output: 0
Constraints:
1 <= nums.length <= 501 <= nums[i] <= 50
Solution
Approach: Counting
An element with remainder 1 can be decreased by 1 and one with remainder 2 can be increased by 1, so each element that is not a multiple of 3 needs exactly one operation, and no fewer are possible. The answer is the number of such elements.
Complexity: O(n) time and O(1) space.
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
return sum(x % 3 != 0 for x in nums)