Open In App

Minimize deletions such that Array sum is divisible by 3

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, the task is to calculate the minimum number of elements to be removed from the array such that the sum of the remaining array elements is divisible by 3.

Examples:

Input:  N = 3, arr[] = {1, 2, 3}
Output: 0
Explanation: 1+2+3 = 6 and it is already divisible by 3. 
So we need to remove 0 elements.

Input: N = 4, arr[] = {3, 6, 2, 2}
Output: 2
Explanation: 3+6+2+2 = 13. 
On removing last two elements, sum would become 9 which is divisible by 3. 
This is minimum number of elements to be removed.

 

Approach: The solution to the problem is based on the following mathematical idea:

  • If the sum is already divisible by 3, no deletions required.
  • If sum%3 = 1 then remove either 1 element (say x) such that x%3 = 1 or two elements (say x and y) such that (x%2 = y%2 = 2) because (2+2)%3 = 1.
  • If sum%2 = 2, then either remove an element (say x) so that x%3 = 2 or remove two elements (say x, y) such that (x%2 = y%2 = 1) because (1+1)%3 = 2 

Follow the below steps to solve this problem:

  • Calculate the sum of all the array elements (say sum).
  • Traverse the array from i = 0 to N-1:
    • If the element is divisible by 3 increase the count of elements divisible by 3.
    • Similarly, store the count of the elements that have remainder = 1 and 2 when divided by 3.
  • Now find the minimum number of deletions required from the above-mentioned conditions.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the number
// of elements to be removed
// to make array sum divisible by 3
int func(int arr[], int n)
{
    int sum = 0;
    int twomod3 = 0, onemod3 = 0;
    for (int i = 0; i < n; i++) {
 
        // Calculating sum of all elements
        sum += arr[i];
 
        // Storing count of elements
        // that leave remainder as 2
        // when divided by 3
        if (arr[i] % 3 == 2)
            twomod3++;
 
        // Storing count of elements
        // that leave remainder as 1
        // when divided by 3
        else if (arr[i] % 3 == 1)
            onemod3++;
    }
 
    // Initializing answer as length of array
    int ans = n;
 
    // If sum is already divisible by 3
    if (sum % 3 == 0)
        ans = 0;
 
    else if (sum % 3 == 1) {
        // Remove at least one element (say x)
        // such that x%3 = 1
        if (onemod3 >= 1) {
            ans = 1;
        }
 
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 2
        else if (twomod3 >= 2) {
            ans = 2;
        }
    }
    else {
        // Remove at least one element (say x)
        // such that x%3 = 2
        if (twomod3 >= 1) {
            ans = 1;
        }
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 1
        else if (onemod3 >= 2) {
            ans = 2;
        }
    }
    ans = min(ans, n);
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 6, 2, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    int ans = func(arr, N);
    cout << ans;
    return 0;
}


C




// C code to implement the approach
 
#include <stdio.h>
 
int min(int a,int b)
{
  if(a>=b)
  {
    return a;
  }
  else
    return b;
}
 
// Function to find the number
// of elements to be removed
// to make array sum divisible by 3
int func(int arr[], int n)
{
    int sum = 0;
    int twomod3 = 0, onemod3 = 0;
    for (int i = 0; i < n; i++) {
 
        // Calculating sum of all elements
        sum += arr[i];
 
        // Storing count of elements
        // that leave remainder as 2
        // when divided by 3
        if (arr[i] % 3 == 2)
            twomod3++;
 
        // Storing count of elements
        // that leave remainder as 1
        // when divided by 3
        else if (arr[i] % 3 == 1)
            onemod3++;
    }
 
    // Initializing answer as length of array
    int ans = n;
 
    // If sum is already divisible by 3
    if (sum % 3 == 0)
        ans = 0;
 
    else if (sum % 3 == 1) {
        // Remove at least one element (say x)
        // such that x%3 = 1
        if (onemod3 >= 1) {
            ans = 1;
        }
 
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 2
        else if (twomod3 >= 2) {
            ans = 2;
        }
    }
    else {
        // Remove at least one element (say x)
        // such that x%3 = 2
        if (twomod3 >= 1) {
            ans = 1;
        }
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 1
        else if (onemod3 >= 2) {
            ans = 2;
        }
    }
    ans = min(ans, n);
    return ans;
}
 
int main() {
 
    // code
     int arr[] = { 3, 6, 2, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
   int ans = func(arr, N);
   printf("%d",ans);
    return 0;
}


Java




// Java program for the above approach
 
import java.util.*;
 
class GFG {
 
// Function to find the number
// of elements to be removed
// to make array sum divisible by 3
static int func(int arr[], int n)
{
    int sum = 0;
    int twomod3 = 0, onemod3 = 0;
    for (int i = 0; i < n; i++) {
 
        // Calculating sum of all elements
        sum += arr[i];
 
        // Storing count of elements
        // that leave remainder as 2
        // when divided by 3
        if (arr[i] % 3 == 2)
            twomod3++;
 
        // Storing count of elements
        // that leave remainder as 1
        // when divided by 3
        else if (arr[i] % 3 == 1)
            onemod3++;
    }
 
    // Initializing answer as length of array
    int ans = n;
 
    // If sum is already divisible by 3
    if (sum % 3 == 0)
        ans = 0;
 
    else if (sum % 3 == 1) {
        // Remove at least one element (say x)
        // such that x%3 = 1
        if (onemod3 >= 1) {
            ans = 1;
        }
 
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 2
        else if (twomod3 >= 2) {
            ans = 2;
        }
    }
    else {
        // Remove at least one element (say x)
        // such that x%3 = 2
        if (twomod3 >= 1) {
            ans = 1;
        }
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 1
        else if (onemod3 >= 2) {
            ans = 2;
        }
    }
    ans = Math.min(ans, n);
    return ans;
}
   
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 6, 2, 2 };
    int N = arr.length;
 
    // Function call
    int ans = func(arr, N);
    System.out.println(ans);
}
}
 
// This code is contributed by code_hunt.


Python3




# Python code to implement the approach
# Function to find the number
# of elements to be removed
# to make array sum divisible by 3
def func(arr,n):
    sum = 0
    twomod3 = 0
    onemod3 = 0
    for i in range(0,n):
        # Calculating sum of all elements
        sum += arr[i]
 
        # Storing count of elements
        # that leave remainder as 2
        # when divided by 3
        if (arr[i] % 3 is 2):
            twomod3+=1;
 
        # Storing count of elements
        # that leave remainder as 1
        # when divided by 3
        elif (arr[i] % 3 is 1):
            onemod3+=1;
 
    #Initializing answer as length of array
    ans = n
 
    # If sum is already divisible by 3
    if (sum % 3 is 0):
        ans = 0
 
    elif (sum % 3 == 1):
        # Remove at least one element (say x)
        # such that x%3 = 1
        if (onemod3 >= 1):
            ans = 1
 
        # Remove at least two elements (x, y)
        # so that x%3 = y%3 = 2
        elif (twomod3 >= 2):
            ans = 2
    else:
        # Remove at least one element (say x)
        # such that x%3 = 2
        if (twomod3 >= 1):
            ans = 1
        # Remove at least two elements (x, y)
        # so that x%3 = y%3 = 1
        elif (onemod3 >= 2):
            ans = 2
    ans = min(ans, n)
    return ans
 
# Driver code
N = 4
arr = [ 3, 6, 2, 2 ]
 
# Function call
ans = func(arr, N)
print(ans)
 
# This code is contributed by ashishsingh13122000.


C#




// C# program to implement
// the above approach
using System;
 
class GFG
{
 
// Function to find the number
// of elements to be removed
// to make array sum divisible by 3
static int func(int[] arr, int n)
{
    int sum = 0;
    int twomod3 = 0, onemod3 = 0;
    for (int i = 0; i < n; i++) {
  
        // Calculating sum of all elements
        sum += arr[i];
  
        // Storing count of elements
        // that leave remainder as 2
        // when divided by 3
        if (arr[i] % 3 == 2)
            twomod3++;
  
        // Storing count of elements
        // that leave remainder as 1
        // when divided by 3
        else if (arr[i] % 3 == 1)
            onemod3++;
    }
  
    // Initializing answer as length of array
    int ans = n;
  
    // If sum is already divisible by 3
    if (sum % 3 == 0)
        ans = 0;
  
    else if (sum % 3 == 1)
    {
       
        // Remove at least one element (say x)
        // such that x%3 = 1
        if (onemod3 >= 1) {
            ans = 1;
        }
  
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 2
        else if (twomod3 >= 2) {
            ans = 2;
        }
    }
    else {
        // Remove at least one element (say x)
        // such that x%3 = 2
        if (twomod3 >= 1) {
            ans = 1;
        }
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 1
        else if (onemod3 >= 2) {
            ans = 2;
        }
    }
    ans = Math.Min(ans, n);
    return ans;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 3, 6, 2, 2 };
    int N = arr.Length;
  
    // Function call
    int ans = func(arr, N);
    Console.Write(ans);
}
}
 
// This code is contributed by avijitmondal1998.


Javascript




<script>
// JS code to implement the approach
// Function to find the number
// of elements to be removed
// to make array sum divisible by 3
function func(arr,n)
{
    var sum = 0;
    var twomod3 = 0;
    var onemod3 = 0;
    for (var i = 0; i < n; i++)
    {
        // Calculating sum of all elements
        sum += arr[i];
 
        // Storing count of elements
        // that leave remainder as 2
        // when divided by 3
        if (arr[i] % 3 == 2)
            twomod3 += 1;
 
        // Storing count of elements
        // that leave remainder as 1
        // when divided by 3
        else if (arr[i] % 3 == 1)
            onemod3+=1;
    }
    //Initializing answer as length of array
    var ans = n;
 
    // If sum is already divisible by 3
    if (sum % 3 == 0)
        ans = 0;
 
    else if (sum % 3 == 1)
    {
        // Remove at least one element (say x)
        // such that x%3 = 1
        if (onemod3 >= 1)
            ans = 1;
 
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 2
        else if (twomod3 >= 2)
            ans = 2;
    }
    else
    {
        //Remove at least one element (say x)
        // such that x%3 = 2
        if (twomod3 >= 1)
            ans = 1;
        // Remove at least two elements (x, y)
        // so that x%3 = y%3 = 1
        else if (onemod3 >= 2)
            ans = 2;
    }
    ans = Math.min(ans, n);
    return ans;
}
 
// Driver code
var N = 4;
var arr = [ 3, 6, 2, 2 ];
 
// Function call
var ans = func(arr, N);
document.write(ans);
 
// This code is contributed by phasing17.
</script>


Output

2

Time Complexity: O(N)
Auxiliary Space: O(1)

Another Approach:

  1. Calculate the sum of all elements in the array.
  2. If the sum is divisible by 3, return 0.
  3. Otherwise, calculate the remainder of the sum when divided by 3. There are three cases:
    a. If the remainder is 1, we need to remove either one element with remainder 1 or two elements with remainder 2.
    b. If the remainder is 2, we need to remove either one element with remainder 2 or two elements with remainder 1.
  4. To find the minimum number of elements to remove, we can keep track of the counts of elements with remainder 1 and 2. If we need to remove two elements, we can remove two with remainder 2 or two with remainder 1, whichever is smaller. If we need to remove one element, we can remove one with remainder 1 or one with remainder 2, whichever is available.
  5. If there are no elements to remove, return 0. Otherwise, return the number of elements to remove.

C++




#include <bits/stdc++.h>
using namespace std;
 
int func(int arr[], int n) {
    int sum = 0;
    int rem1 = 0, rem2 = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
        if (arr[i] % 3 == 1) {
            rem1++;
        } else if (arr[i] % 3 == 2) {
            rem2++;
        }
    }
    if (sum % 3 == 0) {
        return 0;
    } else if (sum % 3 == 1) {
        if (rem1 >= 1) {
            return 1;
        } else if (rem2 >= 2) {
            return 2;
        }
    } else { // sum % 3 == 2
        if (rem2 >= 1) {
            return 1;
        } else if (rem1 >= 2) {
            return 2;
        }
    }
    return -1; // this line should not be reached
}
 
int main() {
    int arr[] = {3, 6, 2, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    int ans = func(arr, n);
    cout << ans << endl; // expected output: 2
    return 0;
}


Java




import java.util.Arrays;
 
public class SumModuloThree {
 
    // Function to determine the minimum removals required to make the sum of the array a multiple of 3
    static int minRemovals(int[] arr) {
        int sum = 0;
        int rem1 = 0, rem2 = 0;
 
        // Calculating the sum and counting remainders
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
            if (arr[i] % 3 == 1) {
                rem1 += 1;
            } else if (arr[i] % 3 == 2) {
                rem2 += 1;
            }
        }
 
        // Checking different cases based on the sum modulo 3
        if (sum % 3 == 0) {
            return 0; // No removals needed
        } else if (sum % 3 == 1) {
            if (rem1 >= 1) {
                return 1; // Remove one element with remainder 1
            } else if (rem2 >= 2) {
                return 2; // Remove two elements with remainder 2
            }
        } else { // sum % 3 == 2
            if (rem2 >= 1) {
                return 1; // Remove one element with remainder 2
            } else if (rem1 >= 2) {
                return 2; // Remove two elements with remainder 1
            }
        }
        return -1; // This line should not be reached
    }
 
    public static void main(String[] args) {
        int[] arr = {3, 6, 2, 2};
        int ans = minRemovals(arr);
         
        // Printing the result
        System.out.println(ans); // Expected output: 2
    }
}


Python3




def func(arr, n):
    sum = 0
    rem1, rem2 = 0, 0
    for i in range(n):
        sum += arr[i]
        if arr[i] % 3 == 1:
            rem1 += 1
        elif arr[i] % 3 == 2:
            rem2 += 1
    if sum % 3 == 0:
        return 0
    elif sum % 3 == 1:
        if rem1 >= 1:
            return 1
        elif rem2 >= 2:
            return 2
    else: # sum % 3 == 2
        if rem2 >= 1:
            return 1
        elif rem1 >= 2:
            return 2
    return -1 # this line should not be reached
 
arr = [3, 6, 2, 2]
n = len(arr)
ans = func(arr, n)
print(ans) # expected output: 2


C#




using System;
 
public class Program {
  public static int Func(int[] arr, int n)
  {
    int sum = 0;
    int rem1 = 0, rem2 = 0;
    for (int i = 0; i < n; i++) {
      sum += arr[i];
      if (arr[i] % 3 == 1) {
        rem1++;
      }
      else if (arr[i] % 3 == 2) {
        rem2++;
      }
    }
    if (sum % 3 == 0) {
      return 0;
    }
    else if (sum % 3 == 1) {
      if (rem1 >= 1) {
        return 1;
      }
      else if (rem2 >= 2) {
        return 2;
      }
    }
    else { // sum % 3 == 2
      if (rem2 >= 1) {
        return 1;
      }
      else if (rem1 >= 2) {
        return 2;
      }
    }
    return -1; // this line should not be reached
  }
  public static void Main()
  {
    int[] arr = { 3, 6, 2, 2 };
    int n = arr.Length;
    int ans = Func(arr, n);
    Console.WriteLine(ans); // expected output: 2
  }
}
 
// This code is contributed by sarojmcy2e


Javascript




function func(arr, n) {
    let sum = 0;
    let rem1 = 0,
        rem2 = 0;
    for (let i = 0; i < n; i++) {
        sum += arr[i];
        if (arr[i] % 3 == 1) {
            rem1++;
        } else if (arr[i] % 3 == 2) {
            rem2++;
        }
    }
    if (sum % 3 == 0) {
        return 0;
    } else if (sum % 3 == 1) {
        if (rem1 >= 1) {
            return 1;
        } else if (rem2 >= 2) {
            return 2;
        }
    } else { // sum % 3 == 2
        if (rem2 >= 1) {
            return 1;
        } else if (rem1 >= 2) {
            return 2;
        }
    }
    return -1; // this line should not be reached
}
 
let arr = [3, 6, 2, 2];
let n = arr.length;
let ans = func(arr, n);
console.log(ans); // expected output: 2


Output

2

Time complexity: O(n)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads