3190. Find Minimum Operations to Make All Elements Divisible by Three LeetCode Solution

In this guide, you will get 3190. Find Minimum Operations to Make All Elements Divisible by Three LeetCode Solution with the best time and space complexity. The solution to Find Minimum Operations to Make All Elements Divisible by Three problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Find Minimum Operations to Make All Elements Divisible by Three solution in C++
  4. Find Minimum Operations to Make All Elements Divisible by Three solution in Java
  5. Find Minimum Operations to Make All Elements Divisible by Three solution in Python
  6. Additional Resources
3190. Find Minimum Operations to Make All Elements Divisible by Three LeetCode Solution image

Problem Statement of Find Minimum Operations to Make All Elements Divisible by Three

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 <= 50
1 <= nums[i] <= 50

Complexity Analysis

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

3190. Find Minimum Operations to Make All Elements Divisible by Three LeetCode Solution in C++

class Solution {
 public:
  int minimumOperations(vector<int>& nums) {
    return ranges::count_if(nums, [](int num) { return num % 3 != 0; });
  }
};
/* code provided by PROGIEZ */

3190. Find Minimum Operations to Make All Elements Divisible by Three LeetCode Solution in Java

class Solution {
  public int minimumOperations(int[] nums) {
    return (int) Arrays.stream(nums).filter(num -> num % 3 != 0).count();
  }
}
// code provided by PROGIEZ

3190. Find Minimum Operations to Make All Elements Divisible by Three LeetCode Solution in Python

class Solution:
  def minimumOperations(self, nums: list[int]) -> int:
    return sum(num % 3 != 0 for num in nums)
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.