Open In App

POTD Solutions | 20 Oct’ 23 | Form a number divisible by 3 using array digits

Last Updated : 22 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

View all POTD Solutions

Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of basic mathematics but will also help you build up problem-solving skills.

POTD-Banner-20

POTD 20 October: Form a number divisible by 3 using array digits

You will be given an array arr of integers of length N. You can construct an integer from two integers by treating the integers as strings and then concatenating them. For example, 19 and 4 can be used to construct 194 and 419.
The task is to find whether it’s possible to construct an integer using all the digits of these numbers such that it would be divisible by 3.
If it is possible then print 1 and if not print 0.

Example:

Input: arr[] = {40, 50, 90}
Output: Yes
Explanation: We can construct a number which is divisible by 3, for example 945000. So the answer is Yes.

Input: arr[] = {1, 4}
Output: No
Explanation: The only possible numbers are 14 and 41, but both of them are not divisible by 3, so the answer is No.

Form a number divisible by 3 using array digits using Divisibility by 3:

The idea is based on the fact that a number is divisible by 3 if the sum of its digits is divisible by 3. So we simply find the sum of array elements. If the sum is divisible by 3, our answer is Yes, else No

Below is the implementation of above approach:

C++




class Solution {
public:
    int isPossible(int n, int arr[])
    {
        // Find remainder of sum when divided by 3
        int remainder = 0;
        for (int i = 0; i < n; i++)
            remainder = (remainder + arr[i]) % 3;
  
        // Return true if remainder is 0.
        return (remainder == 0);
    }
};


Java




class Solution {
    static int isPossible(int n, int arr[])
    {
        // Find remainder of sum when divided by 3
        int remainder = 0;
        for (int i = 0; i < n; i++)
            remainder = (remainder + arr[i]) % 3;
  
        // Return true if remainder is 0.
        if (remainder == 0)
            return 1;
        return 0;
    }
}


Python3




class Solution:
    def isPossible(self, n, arr):
     # Find remainder of sum when divided by 3
        remainder = 0
        for i in range(0, n):
            remainder = (remainder + arr[i]) % 3
  
     # Return true if remainder is 0.
        if (remainder == 0):
            return 1
        return 0


Time Complexity: O(N), where N is the total number of elements in the array
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads