Find the largest multiple of 3 | Set 1 (Using Queue)
Last Updated :
20 May, 2024
Given an array of non-negative integers. Find the largest multiple of 3 that can be formed from array elements.
Examples:
Input: {8,1,9}
Output: "9 8 1"
Input: {8, 1, 7, 6, 0}
Output: "8 7 6 0"
Method 1 (Brute Force) :
The simple & straightforward approach is to generate all the combinations of the elements and keep track of the largest number formed which is divisible by 3.
Time Complexity: O(n x 2n). There will be 2n combinations of array elements. To compare each combination with the largest number so far may take O(n) time.
Auxiliary Space: O(n), To avoid integer overflow, the largest number is assumed to be stored in the form of an array.
Method 2 (Tricky) :
This problem can be solved efficiently with the help of O(n) extra space. This method is based on the following facts about numbers which are multiple of 3.
- A number is multiple of 3 if and only if the sum of digits of number is multiple of 3. For example, let us consider 8760, it is a multiple of 3 because sum of digits is 8 + 7+ 6+ 0 = 21, which is a multiple of 3.
- If a number is multiple of 3, then all permutations of it are also multiple of 3. For example, since 6078 is a multiple of 3, the numbers 8760, 7608, 7068, ..... are also multiples of 3.
- We get the same remainder when we divide the number and sum of digits of the number. For example, if divide number 151 and sum of it digits 7, by 3, we get the same remainder 1.
What is the idea behind above facts?
The value of 10%3 and 100%3 is 1. The same is true for all the higher powers of 10, because 3 divides 9, 99, 999, ... etc.
Let us consider a 3 digit number n to prove above facts. Let the first, second and third digits of n be 'a', 'b' and 'c' respectively. n can be written as
n = 100.a + 10.b + c
Since (10x)%3 is 1 for any x, the above expression gives the same remainder as following expression
1.a + 1.b + c
So the remainder obtained by sum of digits and 'n' is same.
Following is a solution based on the above observation.
- Sort the array in non-decreasing order.
- Take three queues. One for storing elements which on dividing by 3 gives remainder as 0.The second queue stores digits which on dividing by 3 gives remainder as 1. The third queue stores digits which on dividing by 3 gives remainder as 2. Call them as queue0, queue1 and queue2
- Find the sum of all the digits.
- Three cases arise:
- ......4.1 The sum of digits is divisible by 3. Dequeue all the digits from the three queues. Sort them in non-increasing order. Output the array.
- ......4.2 The sum of digits produces remainder 1 when divided by 3.
Remove one item from queue1. If queue1 is empty, remove two items from queue2. If queue2 contains less than two items, the number is not possible. - ......4.3 The sum of digits produces remainder 2 when divided by 3.
Remove one item from queue2. If queue2 is empty, remove two items from queue1. If queue1 contains less than two items, the number is not possible.
- Finally empty all the queues into an auxiliary array. Sort the auxiliary array in non-increasing order. Output the auxiliary array.
The below code works only if the input arrays has numbers from 0 to 9. It can be easily extended for any positive integer array. We just have to modify the part where we sort the array in decreasing order, at the end of code
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// This function puts all elements of 3 queues in the auxiliary array
void populateAux(int aux[], queue<int> queue0, queue<int> queue1,
queue<int> queue2, int* top)
{
// Put all items of first queue in aux[]
while (!queue0.empty()) {
aux[(*top)++] = queue0.front();
queue0.pop();
}
// Put all items of second queue in aux[]
while (!queue1.empty()) {
aux[(*top)++] = queue1.front();
queue1.pop();
}
// Put all items of third queue in aux[]
while (!queue2.empty()) {
aux[(*top)++] = queue2.front();
queue2.pop();
}
}
// The main function that finds the largest possible multiple of
// 3 that can be formed by arr[] elements
int findMaxMultupleOf3(int arr[], int size)
{
// Step 1: sort the array in non-decreasing order
sort(arr, arr + size);
// Create 3 queues to store numbers with remainder 0, 1
// and 2 respectively
queue<int> queue0, queue1, queue2;
// Step 2 and 3 get the sum of numbers and place them in
// corresponding queues
int i, sum;
for (i = 0, sum = 0; i < size; ++i) {
sum += arr[i];
if ((arr[i] % 3) == 0)
queue0.push(arr[i]);
else if ((arr[i] % 3) == 1)
queue1.push(arr[i]);
else
queue2.push(arr[i]);
}
// Step 4.2: The sum produces remainder 1
if ((sum % 3) == 1) {
// either remove one item from queue1
if (!queue1.empty())
queue1.pop();
// or remove two items from queue2
else {
if (!queue2.empty())
queue2.pop();
else
return 0;
if (!queue2.empty())
queue2.pop();
else
return 0;
}
}
// Step 4.3: The sum produces remainder 2
else if ((sum % 3) == 2) {
// either remove one item from queue2
if (!queue2.empty())
queue2.pop();
// or remove two items from queue1
else {
if (!queue1.empty())
queue1.pop();
else
return 0;
if (!queue1.empty())
queue1.pop();
else
return 0;
}
}
int aux[size], top = 0;
// Empty all the queues into an auxiliary array.
populateAux(aux, queue0, queue1, queue2, &top);
// sort the array in non-increasing order
sort(aux, aux + top, greater<int>());
// print the result
for (int i = 0; i < top; ++i)
cout << aux[i] << " ";
return top;
}
int main()
{
int arr[] = { 8, 1, 7, 6, 0 };
int size = sizeof(arr) / sizeof(arr[0]);
if (findMaxMultupleOf3(arr, size) == 0)
cout << "Not Possible";
return 0;
}
C
/* A program to find the largest multiple of 3 from an array of elements */
#include <stdio.h>
#include <stdlib.h>
// A queue node
typedef struct Queue {
int front;
int rear;
int capacity;
int* array;
} Queue;
// A utility function to create a queue with given capacity
Queue* createQueue(int capacity)
{
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->capacity = capacity;
queue->front = queue->rear = -1;
queue->array = (int*)malloc(queue->capacity * sizeof(int));
return queue;
}
// A utility function to check if queue is empty
int isEmpty(Queue* queue)
{
return queue->front == -1;
}
// A function to add an item to queue
void Enqueue(Queue* queue, int item)
{
queue->array[++queue->rear] = item;
if (isEmpty(queue))
++queue->front;
}
// A function to remove an item from queue
int Dequeue(Queue* queue)
{
int item = queue->array[queue->front];
if (queue->front == queue->rear)
queue->front = queue->rear = -1;
else
queue->front++;
return item;
}
// A utility function to print array contents
void printArr(int* arr, int size)
{
int i;
for (i = 0; i < size; ++i)
printf("%d ", arr[i]);
}
int compareAsc(const void* a, const void* b)
{
return *(int*)a > *(int*)b;
}
int compareDesc(const void* a, const void* b)
{
return *(int*)a < *(int*)b;
}
// This function puts all elements of 3 queues in the auxiliary array
void populateAux(int* aux, Queue* queue0, Queue* queue1,
Queue* queue2, int* top)
{
// Put all items of first queue in aux[]
while (!isEmpty(queue0))
aux[(*top)++] = Dequeue(queue0);
// Put all items of second queue in aux[]
while (!isEmpty(queue1))
aux[(*top)++] = Dequeue(queue1);
// Put all items of third queue in aux[]
while (!isEmpty(queue2))
aux[(*top)++] = Dequeue(queue2);
}
// The main function that finds the largest possible multiple of
// 3 that can be formed by arr[] elements
int findMaxMultupleOf3(int* arr, int size)
{
// Step 1: sort the array in non-decreasing order
qsort(arr, size, sizeof(int), compareAsc);
// Create 3 queues to store numbers with remainder 0, 1
// and 2 respectively
Queue* queue0 = createQueue(size);
Queue* queue1 = createQueue(size);
Queue* queue2 = createQueue(size);
// Step 2 and 3 get the sum of numbers and place them in
// corresponding queues
int i, sum;
for (i = 0, sum = 0; i < size; ++i) {
sum += arr[i];
if ((arr[i] % 3) == 0)
Enqueue(queue0, arr[i]);
else if ((arr[i] % 3) == 1)
Enqueue(queue1, arr[i]);
else
Enqueue(queue2, arr[i]);
}
// Step 4.2: The sum produces remainder 1
if ((sum % 3) == 1) {
// either remove one item from queue1
if (!isEmpty(queue1))
Dequeue(queue1);
// or remove two items from queue2
else {
if (!isEmpty(queue2))
Dequeue(queue2);
else
return 0;
if (!isEmpty(queue2))
Dequeue(queue2);
else
return 0;
}
}
// Step 4.3: The sum produces remainder 2
else if ((sum % 3) == 2) {
// either remove one item from queue2
if (!isEmpty(queue2))
Dequeue(queue2);
// or remove two items from queue1
else {
if (!isEmpty(queue1))
Dequeue(queue1);
else
return 0;
if (!isEmpty(queue1))
Dequeue(queue1);
else
return 0;
}
}
int aux[size], top = 0;
// Empty all the queues into an auxiliary array.
populateAux(aux, queue0, queue1, queue2, &top);
// sort the array in non-increasing order
qsort(aux, top, sizeof(int), compareDesc);
// print the result
printArr(aux, top);
return top;
}
// Driver program to test above functions
int main()
{
int arr[] = { 8, 1, 7, 6, 0 };
int size = sizeof(arr) / sizeof(arr[0]);
if (findMaxMultupleOf3(arr, size) == 0)
printf("Not Possible");
return 0;
}
Java
/* Java program to find the largest multiple
of 3 that can be formed from an array
of elements */
import java.util.Arrays;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Collections;
public class Geeks {
// This function puts all elements of 3 queues in the
// array auxiliary
public static int populateAux(int aux[], Queue<Integer> queue0,
Queue<Integer> queue1, Queue<Integer> queue2)
{
int top=0;
// Put all items of first queue in aux[]
while(!queue0.isEmpty())
{
aux[top++]=queue0.remove();
}
// Put all items of second queue in aux[]
while(!queue1.isEmpty())
{
aux[top++]=queue1.remove();
}
// Put all items of third queue in aux[]
while(!queue2.isEmpty())
{
aux[top++]=queue2.remove();
}
//Return number of integer added to aux[]
return top;
}
// The main function that finds the largest possible multiple of
// 3 that can be formed by arr[] elements
public static boolean findMaxMultupleOf3(int arr[])
{
// Step 1: sort the array in non-decreasing order
Arrays.sort(arr);
// Create 3 queues to store numbers with remainder 0, 1
// and 2 respectively
Queue<Integer> queue0=new LinkedList<>();
Queue<Integer> queue1=new LinkedList<>();
Queue<Integer> queue2=new LinkedList<>();
// Step 2 and 3 get the sum of numbers and place them in
// corresponding queues
int sum=0;
for (int i = 0; i < arr.length; ++i)
{
sum += arr[i];
if ((arr[i] % 3) == 0)
queue0.add(arr[i]);
else if ((arr[i] % 3) == 1)
queue1.add(arr[i]);
else
queue2.add(arr[i]);
}
// Step 4.2: The sum produces remainder 1
if ((sum % 3) == 1)
{
// either remove one item from queue1
if (!queue1.isEmpty())
queue1.remove();
// or remove two items from queue2
else
{
if (!queue2.isEmpty())
queue2.remove();
else
return false;
if (!queue2.isEmpty())
queue2.remove();
else
return false;
}
}
// Step 4.3: The sum produces remainder 2
else if ((sum % 3) == 2)
{
// either remove one item from queue2
if (!queue2.isEmpty())
queue2.remove();
// or remove two items from queue1
else
{
if (!queue1.isEmpty())
queue1.remove();
else
return false;
if (!queue1.isEmpty())
queue1.remove();
else
return false;
}
}
int aux[]=new int[arr.length];
// Empty all the queues into an auxiliary array
// and get the number of integers added to aux[]
int top=populateAux(aux,queue0,queue1,queue2);
// sort the array in non-increasing order
Arrays.sort(aux,0,top);
// print the result
for (int i = top-1; i>=0; i--)
System.out.print(aux[i]+" ") ;
return true;
}
public static void main(String args[])
{
int arr[] = { 8, 1, 7, 6, 0 };
if (!findMaxMultupleOf3(arr))
System.out.println("Not possible") ;
}
}
// This code is contributed by Gaurav Tiwari
Python
# Python3 program to find the largest multiple
# of 3 that can be formed from an array
# of elements
aux = []
# This function puts all elements of 3 queues in the
# array auxiliary
def populateAux(queue0, queue1, queue2):
global aux
top = 0
# Put all items of first queue in aux[]
while(len(queue0) > 0):
aux[top] = queue0.pop(0)
top += 1
# Put all items of second queue in aux[]
while(len(queue1) != 0):
aux[top] = queue1.pop(0)
top += 1
# Put all items of third queue in aux[]
while(len(queue2) != 0):
aux[top] = queue2.pop(0)
top += 1
# Return number of integer added to aux[]
return top
# The main function that finds the largest possible multiple of
# 3 that can be formed by arr[] elements
def findMaxMultupleOf3(arr):
global aux
# Step 1: sort the array in non-decreasing order
arr.sort()
# Create 3 queues to store numbers with remainder 0, 1
# and 2 respectively
queue0 = []
queue1 = []
queue2 = []
# Step 2 and 3 get the sum of numbers and place them in
# corresponding queues
sum = 0
for i in range(len(arr)):
sum += arr[i]
if ((arr[i] % 3) == 0):
queue0.append(arr[i])
elif ((arr[i] % 3) == 1):
queue1.append(arr[i])
else:
queue2.append(arr[i])
# Step 4.2: The sum produces remainder 1
if ((sum % 3) == 1):
# either remove one item from queue1
if (len(queue1) != 0):
queue1.pop(0)
# or remove two items from queue2
else:
if (len(queue2) != 0):
queue2.pop(0)
else:
return False
if (len(queue2) != 0):
queue2.pop(0)
else:
return False
# Step 4.3: The sum produces remainder 2
elif ((sum % 3) == 2):
# either remove one item from queue2
if (len(queue2) != 0):
queue2.pop(0)
# or remove two items from queue1
else:
if (len(queue1) != 0):
queue1.pop(0)
else:
return False
if (len(queue1) != 0):
queue1.pop(0)
else:
return False
aux = [0 for i in range(len(arr))]
# Empty all the queues into an auxiliary array
# and get the number of integers added to aux[]
top = populateAux(queue0, queue1, queue2)
# sort the array in non-increasing order
aux.sort(reverse=True)
# print the result
for i in range(0, top):
print(aux[i], end=" ")
return True
# Driver code
arr = [8, 1, 7, 6, 0]
if (not findMaxMultupleOf3(arr)):
print("Not possible")
# This code is contributed by phasing17
C#
/* C# program to find the largest multiple
of 3 that can be formed from an array
of elements */
using System;
using System.Collections.Generic;
class Geeks
{
// This function puts all elements of 3 queues in the
// array auxiliary
public static int populateAux(int []aux, Queue<int> queue0,
Queue<int> queue1, Queue<int> queue2)
{
int top = 0;
// Put all items of first queue in aux[]
while(queue0.Count != 0)
{
aux[top++] = queue0.Dequeue();
}
// Put all items of second queue in aux[]
while(queue1.Count != 0)
{
aux[top++] = queue1.Dequeue();
}
// Put all items of third queue in aux[]
while(queue2.Count != 0)
{
aux[top++] = queue2.Dequeue();
}
//Return number of integer added to aux[]
return top;
}
// The main function that finds the largest possible multiple of
// 3 that can be formed by arr[] elements
public static bool findMaxMultupleOf3(int []arr)
{
// Step 1: sort the array in non-decreasing order
Array.Sort(arr);
// Create 3 queues to store numbers with remainder 0, 1
// and 2 respectively
Queue<int> queue0 = new Queue<int>();
Queue<int> queue1 = new Queue<int>();
Queue<int> queue2 = new Queue<int>();
// Step 2 and 3 get the sum of numbers and place them in
// corresponding queues
int sum=0;
for (int i = 0; i < arr.Length; ++i)
{
sum += arr[i];
if ((arr[i] % 3) == 0)
queue0.Enqueue(arr[i]);
else if ((arr[i] % 3) == 1)
queue1.Enqueue(arr[i]);
else
queue2.Enqueue(arr[i]);
}
// Step 4.2: The sum produces remainder 1
if ((sum % 3) == 1)
{
// either remove one item from queue1
if (queue1.Count != 0)
queue1.Dequeue();
// or remove two items from queue2
else
{
if (queue2.Count != 0)
queue2.Dequeue();
else
return false;
if (queue2.Count != 0)
queue2.Dequeue();
else
return false;
}
}
// Step 4.3: The sum produces remainder 2
else if ((sum % 3) == 2)
{
// either remove one item from queue2
if (queue2.Count != 0)
queue2.Dequeue();
// or remove two items from queue1
else
{
if (queue1.Count != 0)
queue1.Dequeue();
else
return false;
if (queue1.Count != 0)
queue1.Dequeue();
else
return false;
}
}
int []aux = new int[arr.Length];
// Empty all the queues into an auxiliary array
// and get the number of integers added to aux[]
int top = populateAux(aux,queue0,queue1,queue2);
// sort the array in non-increasing order
Array.Sort(aux,0,top);
// print the result
for (int i = top-1; i >= 0; i--)
Console.Write(aux[i]+" ") ;
return true;
}
// Driver code
public static void Main()
{
int []arr = { 8, 1, 7, 6, 0 };
if (!findMaxMultupleOf3(arr))
Console.WriteLine("Not possible") ;
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
/* Javascript program to find the largest multiple
of 3 that can be formed from an array
of elements */
// This function puts all elements of 3 queues in the
// array auxiliary
function populateAux(aux, queue0, queue1, queue2)
{
let top = 0;
// Put all items of first queue in aux[]
while(queue0.length != 0)
{
aux[top++] = queue0.shift();
}
// Put all items of second queue in aux[]
while(queue1.length != 0)
{
aux[top++] = queue1.shift();
}
// Put all items of third queue in aux[]
while(queue2.length != 0)
{
aux[top++] = queue2.shift();
}
//Return number of integer added to aux[]
return top;
}
// The main function that finds the largest possible multiple of
// 3 that can be formed by arr[] elements
function findMaxMultupleOf3(arr)
{
// Step 1: sort the array in non-decreasing order
arr.sort(function(a, b){return a - b;});
// Create 3 queues to store numbers with remainder 0, 1
// and 2 respectively
let queue0 = [];
let queue1 = [];
let queue2 = [];
// Step 2 and 3 get the sum of numbers and place them in
// corresponding queues
let sum = 0;
for (let i = 0; i < arr.length; ++i)
{
sum += arr[i];
if ((arr[i] % 3) == 0)
queue0.push(arr[i]);
else if ((arr[i] % 3) == 1)
queue1.push(arr[i]);
else
queue2.push(arr[i]);
}
// Step 4.2: The sum produces remainder 1
if ((sum % 3) == 1)
{
// either remove one item from queue1
if (queue1.length != 0)
queue1.shift();
// or remove two items from queue2
else
{
if (queue2.length != 0)
queue2.shift();
else
return false;
if (queue2.length != 0)
queue2.shift();
else
return false;
}
}
// Step 4.3: The sum produces remainder 2
else if ((sum % 3) == 2)
{
// either remove one item from queue2
if (queue2.length != 0)
queue2.shift();
// or remove two items from queue1
else
{
if (queue1.length != 0)
queue1.shift();
else
return false;
if (queue1.length != 0)
queue1.shift();
else
return false;
}
}
let aux=new Array(arr.length);
// Empty all the queues into an auxiliary array
// and get the number of integers added to aux[]
let top=populateAux(aux, queue0, queue1, queue2);
// sort the array in non-increasing order
aux.sort(function(a, b){return a - b;});
// print the result
for (let i = top - 1; i >= 0; i--)
document.write(aux[i]+" ") ;
return true;
}
// Driver code
let arr = [ 8, 1, 7, 6, 0 ];
if (!findMaxMultupleOf3(arr))
document.write("Not possible") ;
// This code is contributed by rag2127.
</script>
The above method can be optimized in following ways.
- We can use Heap Sort or Merge Sort to make the time complexity O(nLogn).
- We can avoid extra space for queues. We know at most two items will be removed from the input array. So we can keep track of two items in two variables.
- At the end, instead of sorting the array again in descending order, we can print the ascending sorted array in reverse order. While printing in reverse order, we can skip the two elements to be removed.
Time Complexity: O(nLogn), assuming a O(nLogn) algorithm is used for sorting.
Find the largest multiple of 3 | Set 2 (In O(n) time and O(1) space)
Similar Reads
Find the largest possible k-multiple set
Given an array containing distinct positive integers and an integer k. The task is to find the largest possible k-multiple set from the array of given elements. A set is called a k-multiple set if no two elements of the set i.e., x, y exits such that y = x*k.There can be multiple answers. You can Pr
5 min read
Smallest multiple of N formed using the given set of digits
Given a set of digits S and an integer N, the task is to find the smallest positive integer if exists which contains only the digits from S and is a multiple of N. Note that the digits from the set can be used multiple times. Examples: Input: S[] = {5, 2, 3}, N = 12 Output: 252 We can observe that 2
10 min read
Find the largest multiple of 3 from array of digits | Set 2 (In O(n) time and O(1) space)
Given an array of digits (contain elements from 0 to 9). Find the largest number that can be made from some or all digits of array and is divisible by 3. The same element may appear multiple times in the array, but each element in the array may only be used once. Examples: Input : arr[] = {5, 4, 3,
15+ min read
Find Multiples of 2 or 3 or 5 less than or equal to N
Given an integer N . The task is to count all such numbers that are less than or equal to N which are divisible by any of 2 or 3 or 5.Note: If a number less than N is divisible by both 2 or 3, or 3 or 5, or all of 2,3 and 5 then also it should be counted only once.Examples: Input : N = 5 Output : 4
8 min read
Interleave the first half of the queue with second half
Given a Queue of even size. Your task is to rearrange the queue by interleaving its first half with the second half.Note: Interleaving means place the first element from the first half and then first element from the 2nd half and again 2nd element from the first half and then second element from the
12 min read
Find the largest possible value of K such that K modulo X is Y
Given three integers N, X, and Y, the task is to find out the largest positive integer K such that K % X = Y where 0 ⤠K ⤠N. Print -1 if no such K exists. Examples: Input: N = 15, X = 10, Y = 5Output:15Explanation:As 15 % 10 = 5 Input: N = 187, X = 10, Y = 5Output: 185 Recommended: Please try your
10 min read
Priority Queue using Linked List
Implement Priority Queue using Linked Lists. The Linked List should be so created so that the highest priority ( priority is assigned from 0 to n-1 where n is the number of elements, where 0 means the highest priority and n-1 being the least ) element is always at the head of the list. The list is a
11 min read
Find the Kth Largest Tribonacci Number Node in a Singly Linked List
Given a singly linked list containing integers, the task is to find the Kth largest Tribonacci number in the linked list. Note: A Tribonacci number is a series of numbers where each number is the sum of the three preceding numbers. The Tribonacci Sequence: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 2
10 min read
Find Nth number in a sequence which is not a multiple of a given number
Given four integers A, N, L and R, the task is to find the N th number in a sequence of consecutive integers from L to R which is not a multiple of A. It is given that the sequence contain at least N numbers which are not divisible by A and the integer A is always greater than 1. Examples: Input: A
9 min read
Kth number from the set of multiples of numbers A, B and C
Given four integers A, B, C and K. Assume that all the multiples of A, B and C are stored in a set in sorted order with no duplicates, now the task is to find the Kth element from that set.Examples: Input: A = 1, B = 2, C = 3, K = 4 Output: 4 The required set is {1, 2, 3, 4, 5, ...}Input: A = 2, B =
15+ min read