Check if any permutation of array contains sum of every adjacent pair not divisible by 3

Given an array arr[] consisting of N integers, the task is to check if any permutation of the array elements exists where the sum of every pair of adjacent elements is not divisible by 3. If it is possible, then print “Yes”. Otherwise, print “No”.

Examples:

Input: arr[] = {1, 2, 3, 3}
Output: Yes
Explanation:
Since there exist at least 1 combination {3, 2, 3, 1} where sum of every adjacent pairs is not divisible by 3.

Input: arr[] = {3, 6, 1, 9}
Output: No

Naive Approach: The simplest approach is to generate all permutations of the given array and check if there exists an arrangement in which the sum of no two adjacent elements is divisible by 3. If it is found to be true, then print “Yes”. Otherwise, print “No”.



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

Efficient Approach: To optimize the above approach, the idea is to observe that the only possible remainders for all the array elements i.e., {0, 1, 2}. To segregate these three numbers in such a way that the sum of two adjacent elements is not divisible by 3. Follow the steps below:

  1. Count all the numbers into three parts having remainder 0, 1, and 2. Let the count be a, b, and c respectively.
  2. Now arrange the numbers having remainder as 0 with the numbers having remainder as 1 or 2 such that their sum will not be divisible by 3. Below are the conditions where this condition can be true: 
    • If a ≥ 1 and a ≤ b + c + 1
    • If a and b both are equals to 0 and c > 0
    • If a and c both are equals to 0 and b > 0
  3. If there is no way to arrange all the numbers in the above way then there is no permutation such that their sum of adjacent elements is not divisible by 3. Therefore, print “No”.
  4. If the condition in Step 2 is found to be true, then print “Yes”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to checks if any permutation
// of the array exists whose sum of
// adjacent pairs is not divisible by 3
void factorsOf3(int arr[], int N)
{
    int a = 0, b = 0, c = 0;
    for (int i = 0; i < N; i++) {
 
        // Count remainder 0
        if (arr[i] % 3 == 0)
            a++;
 
        // Count remainder 1
        else if (arr[i] % 3 == 1)
            b++;
 
        // Count remainder 2
        else if (arr[i] % 3 == 2)
            c++;
    }
 
    // Condition for valid arrangements
    if (a >= 1 && a <= b + c + 1)
        cout << "Yes" << endl;
    else if (a == 0 && b == 0 && c > 0)
        cout << "Yes" << endl;
    else if (a == 0 && c == 0 && b > 0)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 3, 3 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    factorsOf3(arr, N);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for
// the above approach
class GFG{
 
// Function to checks if any permutation
// of the array exists whose sum of
// adjacent pairs is not divisible by 3
static void factorsOf3(int arr[], int N)
{
  int a = 0, b = 0, c = 0;
  for (int i = 0; i < N; i++)
  {
    // Count remainder 0
    if (arr[i] % 3 == 0)
      a++;
 
    // Count remainder 1
    else if (arr[i] % 3 == 1)
      b++;
 
    // Count remainder 2
    else if (arr[i] % 3 == 2)
      c++;
  }
 
  // Condition for valid arrangements
  if (a >= 1 && a <= b + c + 1)
    System.out.print("Yes" + "\n");
  else if (a == 0 && b == 0 && c > 0)
    System.out.print("Yes" + "\n");
  else if (a == 0 && c == 0 && b > 0)
    System.out.print("Yes" + "\n");
  else
    System.out.print("No" + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array arr[]
  int arr[] = {1, 2, 3, 3};
 
  int N = arr.length;
 
  // Function Call
  factorsOf3(arr, N);
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to checks if any permutation
# of the array exists whose sum of
# adjacent pairs is not divisible by 3
def factorsOf3(arr, N):
 
    a = 0
    b = 0
    c = 0
 
    for i in range(N):
 
        # Count remainder 0
        if (arr[i] % 3 == 0):
            a += 1
        # Count remainder 1
        elif (arr[i] % 3 == 1):
            b += 1
        # Count remainder 2
        elif (arr[i] % 3 == 2):
            c += 1
 
    # Condition for valid arrangements
    if (a >= 1 and a <= b + c + 1):
        print("Yes")
    elif (a == 0 and b == 0 and c > 0):
        print("Yes")
    elif (a == 0 and c == 0 and b > 0):
        print("Yes")
    else:
        print("No")
 
# Driver Code
 
# Given array arr[]
arr = [ 1, 2, 3, 3 ]
N = len(arr)
 
# Function call
factorsOf3(arr, N)
 
# This code is contributed by Shivam Singh

chevron_right


Output: 

Yes



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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : SHIVAMSINGH67, Rajput-Ji