Find Minimum Operations to Make All Elements Divisible by Three

Language Options

C++ Solution |
Python Solution

Problem Description

You’ve got a list of numbers, and you want to make them all divisible by three. The task is to find the minimum number of operations required to achieve this. An operation consists of incrementing or decrementing a number by one.

Imagine you’re at a party, and everyone is dancing in groups of three. But wait! Some party-goers are left out, and you need to either pull them in or send them home. Your job is to figure out how many people need to be adjusted to make sure everyone is in a group of three.

Code Solution

Here’s the Python solution to this delightful conundrum:


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

Approach

The approach here is straightforward: we iterate through the list of numbers and check if each number is divisible by three. If it’s not, we count it as needing an operation. The final count gives us the minimum operations required to make all numbers divisible by three.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n)
Space Complexity O(1)

Real-World Example

Let’s say you’re organizing a game night with your friends. You have 10 friends, but only 3 can play a game at a time. You need to figure out how many friends need to be sent home or called in to make sure everyone can play in groups of three. If you have 10 friends, you can only form 3 groups of 3, leaving 1 friend out. So, you need to adjust your group to make it work. This is essentially what the problem is asking you to do with numbers!

Similar Problems

If you enjoyed this problem, you might also like these: