Find Minimum Operations to Make All Elements Divisible by Three solution and explanation
9 more videos on this problem
Find Minimum Operations to Make All Elements Divisible by Three - Leetcode 3190 - PythonNeetCodeIO · 5:48 · 4K views
LeetCode 3190 | Find Minimum Operations to Make All Elements Divisible by Three | #leetcodecontestAlgo Horizon · 2:50 · 1K views
Daily Leetcode #2062: Nov 22, 2025 - 3190. Find Minimum Operations to Make All Elements Div...Programming Live with Larry · 3:48 · 297 views
Find Minimum Operations to Make All Elements Divisible by Three | LeetCode 3190 | Developer CoderDeveloper Coder · 4:57 · 134 views
Find Minimum Operations to Make All Elements Divisible by Three - Leetcode 3190 - Javacodewithsitaram · 15:10 · 123 views
LeetCode 3190. Find Minimum Operations to Make All Elements Divisible by ThreeEdTech · 9:27 · 119 views
LeetCode 3190: Find Minimum Operations to Make All Elements Divisible by 3 | C# | Modular ArithmeticCode Scribbler · 3:26 · 85 views
Find Minimum Operations to Make All Elements Divisible by Three | Leetcode 3190 | Approach + Code.Pirai's Academy · 3:50 · 85 views
3190. Find Minimum Operations to Make All Elements Divisible by Three | Leetcode Daily - PythonLeetcode Daily · 6:56 · 59 views
LeetCode 3190 – Find Minimum Operations to Make All Elements Divisible by Three | Easy Java SolutionVeer Codes · 5:56 · 29 views
The problem
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
Approach overview
Problem Overview: You get an integer array. In one operation you can increment or decrement any element by 1. The goal is to make every value divisible by 3 using the minimum number of operations.
The key observation: divisibility by 3 depends only on the remainder when dividing by 3. If num % 3 == 0, the element already satisfies the requirement. If the remainder is 1 or 2, you adjust the number by the shortest distance to the nearest multiple of 3.
Approach 1: Modulo and Adjustment (O(n) time, O(1) space)
Iterate through the array and compute r = num % 3. If r == 0, no operation is required. If r == 1, you can subtract 1 to reach the previous multiple of 3. If r == 2, you can add 1 to reach the next multiple of 3. Each non‑zero remainder therefore costs exactly one operation. Accumulate the number of such adjustments while scanning the array once.
This works because multiples of 3 are spaced exactly three units apart. Any number with remainder 1 or 2 is always one step away from some valid multiple. The algorithm uses simple arithmetic and a single pass over the array, which keeps the implementation clean and efficient. Since only a few integer variables are used, the extra space remains constant.
Approach 2: Array to Direct Count (O(n) time, O(1) space)
This approach focuses purely on counting remainders. Traverse the array and classify each element by num % 3. Maintain counters for remainder 1 and remainder 2. Each occurrence contributes one operation because you either decrement a remainder‑1 number or increment a remainder‑2 number.
After processing the entire array, the total operations equal count1 + count2. The logic is slightly more explicit than the previous approach and can be helpful when reasoning about groups of elements rather than individual transformations.
Both approaches rely on modular arithmetic and sequential iteration, common techniques when working with array problems that involve divisibility or remainder patterns in math-based logic.
Recommended for interviews: The modulo adjustment approach. It shows you immediately recognized the remainder pattern and converted the problem into a simple linear scan with constant space. The counting variant demonstrates the same insight but is slightly more verbose. Interviewers typically expect the O(n) pass using num % 3.
Approach 1: Approach 1: Modulo and Adjustment
This approach involves iterating through the array and checking the remainder when each element is divided by 3.
- If the remainder is 0, no operations are needed.
- If the remainder is 1, you can either subtract 1 to make it divisible by 3.
- If the remainder is 2, you can add 1 to make it divisible by 3.
Count these operations and sum them up to get the total minimum operations required.
def min_operations_divisible_by_three(nums):
operations = 0
for num in nums:
remainder = num % 3
if remainder == 1 or remainder == 2:
operations += 1
return operations
nums = [1, 2, 3, 4]
print(min_operations_divisible_by_three(nums))public class MinOperations {
public static int minOperationsDivisibleByThree(int[] nums) {
int operations = 0;
for (int num : nums) {
int remainder = num % 3;
if (remainder == 1 || remainder == 2) {
operations += 1;
}
}
return operations;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
System.out.println(minOperationsDivisibleByThree(nums));
}
}#include <iostream>
#include <vector>
using namespace std;
int minOperationsDivisibleByThree(vector<int>& nums) {
int operations = 0;
for (int num : nums) {
int remainder = num % 3;
if (remainder == 1 || remainder == 2) {
operations += 1;
}
}
return operations;
}
int main() {
vector<int> nums = {1, 2, 3, 4};
cout << minOperationsDivisibleByThree(nums) << endl;
return 0;
}function minOperationsDivisibleByThree(nums) {
let operations = 0;
for (let num of nums) {
let remainder = num % 3;
if (remainder == 1 || remainder == 2) {
operations += 1;
}
}
return operations;
}
const nums = [1, 2, 3, 4];
console.log(minOperationsDivisibleByThree(nums));#include <stdio.h>
int minOperationsDivisibleByThree(int* nums, int numsSize) {
int operations = 0;
for (int i = 0; i < numsSize; i++) {
int remainder = nums[i] % 3;
if (remainder == 1) {
operations += 1;
} else if (remainder == 2) {
operations += 1;
}
}
return operations;
}
int main() {
int nums[] = {1, 2, 3, 4};
int result = minOperationsDivisibleByThree(nums, 4);
printf("%d\n", result);
return 0;
}using System;
public class MinOperations {
public static int MinOperationsDivisibleByThree(int[] nums) {
int operations = 0;
foreach (int num in nums) {
int remainder = num % 3;
if (remainder == 1 || remainder == 2) {
operations += 1;
}
}
return operations;
}
public static void Main(string[] args) {
int[] nums = { 1, 2, 3, 4 };
Console.WriteLine(MinOperationsDivisibleByThree(nums));
}
}This function iterates over the list, calculates the remainder of each element divided by 3, and adjusts the operation count accordingly.
Time Complexity: O(n) where n is the number of elements in nums.
Space Complexity: O(1), as we do not allocate additional space aside from fixed variables.
Approach 2: Approach 2: Array to Direct Count
This approach counts how many numbers in the array have remainders of 1 or 2, thus directly determining the operations needed without checking each element individually in a loop, leveraging the properties of remainders.
def min_operations_divisible_by_three(nums):
count1, count2 = 0, 0
for num in nums:
remainder = num % 3
if remainder == 1:
count1 += 1
elif remainder == 2:
count2 += 1
return count1 + count2
nums = [1, 2, 3, 4]
print(min_operations_divisible_by_three(nums))public class MinOperations {
public static int minOperationsDivisibleByThree(int[] nums) {
int count1 = 0, count2 = 0;
for (int num : nums) {
int remainder = num % 3;
if (remainder == 1) {
count1++;
} else if (remainder == 2) {
count2++;
}
}
return count1 + count2;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4};
System.out.println(minOperationsDivisibleByThree(nums));
}
}#include <iostream>
#include <vector>
using namespace std;
int minOperationsDivisibleByThree(vector<int>& nums) {
int count1 = 0, count2 = 0;
for (int num : nums) {
int remainder = num % 3;
if (remainder == 1) {
count1++;
} else if (remainder == 2) {
count2++;
}
}
return count1 + count2;
}
int main() {
vector<int> nums = {1, 2, 3, 4};
cout << minOperationsDivisibleByThree(nums) << endl;
return 0;
}function minOperationsDivisibleByThree(nums) {
let count1 = 0, count2 = 0;
for (let num of nums) {
let remainder = num % 3;
if (remainder == 1) {
count1++;
} else if (remainder == 2) {
count2++;
}
}
return count1 + count2;
}
const nums = [1, 2, 3, 4];
console.log(minOperationsDivisibleByThree(nums));#include <stdio.h>
int minOperationsDivisibleByThree(int* nums, int numsSize) {
int count1 = 0, count2 = 0;
for (int i = 0; i < numsSize; i++) {
int remainder = nums[i] % 3;
if (remainder == 1) {
count1++;
} else if (remainder == 2) {
count2++;
}
}
return count1 + count2;
}
int main() {
int nums[] = {1, 2, 3, 4};
int result = minOperationsDivisibleByThree(nums, 4);
printf("%d\n", result);
return 0;
}using System;
public class MinOperations {
public static int MinOperationsDivisibleByThree(int[] nums) {
int count1 = 0, count2 = 0;
foreach (int num in nums) {
int remainder = num % 3;
if (remainder == 1) {
count1++;
} else if (remainder == 2) {
count2++;
}
}
return count1 + count2;
}
public static void Main(string[] args) {
int[] nums = { 1, 2, 3, 4 };
Console.WriteLine(MinOperationsDivisibleByThree(nums));
}
}Python approach using two counters for elements with remainder 1 and 2.
Time Complexity: O(n)
Space Complexity: O(1)
Approach 3: Counting
We directly iterate through the array nums. For each element x, if x bmod 3 neq 0, there are two cases:
- If
x bmod 3 = 1, we can decreasexby1to make itx - 1, which is divisible by3. - If
x bmod 3 = 2, we can increasexby1to make itx + 1, which is divisible by3.
Therefore, we only need to count the number of elements in the array that are not divisible by 3 to get the minimum number of operations.
The time complexity is O(n), where n is the length of the array nums. The space complexity is O(1).
function minimumOperations(nums: number[]): number {
return nums.reduce((acc, x) => acc + (x % 3 !== 0 ? 1 : 0), 0);
}func minimumOperations(nums []int) (ans int) {
for _, x := range nums {
if x%3 != 0 {
ans++
}
}
return
}impl Solution {
pub fn minimum_operations(nums: Vec<i32>) -> i32 {
nums.iter().filter(|&&x| x % 3 != 0).count() as i32
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Modulo and Adjustment | Time Complexity: O(n) where n is the number of elements in nums. |
| Approach 2: Array to Direct Count | Time Complexity: O(n) |
| Counting | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Modulo and Adjustment | O(n) | O(1) | General solution. Best when you directly compute remainder and adjust each value. |
| Array to Direct Count | O(n) | O(1) | Useful when reasoning about remainder groups or counting transformations. |
Frequently asked questions
Is Find Minimum Operations to Make All Elements Divisible by Three easy or hard?
The problem is classified as Easy on LeetCode. It mainly tests understanding of modular arithmetic and linear array traversal rather than advanced data structures or algorithms.
Find Minimum Operations to Make All Elements Divisible by Three Python/Java solution
In Python or Java, iterate through the array and compute num % 3 for each value. If the remainder is not zero, increment the operation counter by one. This straightforward loop achieves O(n) time and O(1) space while keeping the implementation concise.
How to solve Find Minimum Operations to Make All Elements Divisible by Three in O(n)?
Traverse the array and compute the remainder of each element using num % 3. If the remainder is 1 or 2, add one operation to the result since either incrementing or decrementing by 1 makes the number divisible by 3. Continue until all elements are processed, resulting in a linear O(n) pass.
What is the best approach for Find Minimum Operations to Make All Elements Divisible by Three?
The best approach is using modulo arithmetic. Iterate through the array, compute num % 3, and count how many elements have remainder 1 or 2. Each such element requires one adjustment (increment or decrement by 1). This gives an O(n) time and O(1) space solution.
Is Find Minimum Operations to Make All Elements Divisible by Three asked at Google/Amazon/Meta?
This specific problem is categorized as an easy array and math problem and is commonly used as a warm‑up question in coding platforms like LeetCode. Variations involving divisibility, modular arithmetic, and array traversal frequently appear in interviews at companies such as Amazon and Google.
What data structure is used in Find Minimum Operations to Make All Elements Divisible by Three?
The problem primarily uses a simple array traversal combined with modular arithmetic. No complex data structures are required, and the algorithm operates with constant extra space using a few counters or variables.
What is the time complexity of Find Minimum Operations to Make All Elements Divisible by Three?
The optimal solution runs in O(n) time because the algorithm scans the array once and performs constant-time arithmetic per element. Space complexity is O(1) since only a few counters or variables are maintained.
