Split an array into groups of 3 such that X3 is divisible by X2 and X2 is divisible by X1

Given an array A containing N elements (N is divisible by 3), the task is to split the numbers into groups of 3, let the group have 3 elements X1, X2 and X3, the following conditions should be true for the group:

  • X1, X2 and X3 are pairwise distinct
  • X3 is divisible by X2
  • X2 is divisible by X1

Print -1 if splitting the array into N/3 Such groups is not possible.

Note: Elements of the array will lie in the range 1 to 6 (inclusive).

Examples:

Input : N = 6, A[] = {2, 2, 1, 1, 4, 6}
Output : 1 2 4
         1 2 6
Explanation: 
Group 1: Pairs = {(1,2), (2,4), (1,4)}
All pairs are distinct, 
4 is divisible by 2 and 2 by 1.
Group 2: Pairs = {(1,2), (2,6), (1,6)}
All pairs are distinct, 
6 is divisible by 2 and 2 by 1.

Input : N = 6, A[] = {1, 1, 1, 6, 6, 3}
Output : -1

Approach:

Since the values of the array are between 1 and 6, only the following kind of groups can be made:

  • 1 2 4
  • 1 2 6
  • 1 3 6

Start of by counting the frequency of each element. Since 1 is common across all groups, it must occur exactly N/3 times. 4 can be put into only the first kind of group, which always contains 2. So the count of 2 should be greater than the count of 4. The remaining 2 can be put in only the second kind of groups. Now, the remaining numbers have to be put in the third kind of groups. If at any point the count is less than required, the answer would be -1.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to split array in groups of 3
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the groups after
// spliting array in groups of 3
void printGroups(int n, int a[])
{
    int ct[7] = { 0 }, grps = n / 3, i;
  
    // Count occurence of each element
    for (i = 0; i < n; i++)
        ct[a[i]]++;
  
    // Check if it is possible to form the groups
    if (ct[1] != grps || (ct[4] + ct[6]) != grps 
              || (ct[2] + ct[3]) != grps || ct[4] > ct[2]) 
    {
        cout << -1;
        return;
    }
  
    // Print groups that end at 4
    for (i = 0; i < ct[4]; i++)
        cout << "1 2 4\n";
  
    // Print groups that end at 6, with 2
    // in the middle
    for (i = 0; i < ct[2] - ct[4]; i++)
        cout << "1 2 6\n";
  
    // Print groups that have a 3 in the middle
    for (i = 0; i < ct[3]; i++)
        cout << "1 3 6\n";
}
  
// Driver Code
int main()
{
    int n = 6;
    int a[n] = { 2, 2, 1, 1, 4, 6 };
  
    printGroups(n, a);
  
    return 0;
}

chevron_right


Output:

1 2 4
1 2 6

Time Complexity: O(N)



My Personal Notes arrow_drop_up