Skip to content
Related Articles

Related Articles

Improve Article

Sort N triplets

  • Last Updated : 24 Oct, 2021
Geek Week

Given an array arr[ ] of N triplets, the task is to order the triplets in descending order. Triplet X will have higher priority than triplet Y if and only if all elements of triplet X will be greater than or equal to the corresponding element of triplet Y. Print Impossible if triplets can’t be ordered.

Examples:

Input: arr = {{1, 2, 3}, {1, 3, 4}, {4, 7, 4}}
Output: {{4, 7, 4}, {1, 3, 4}, {1, 2, 3}}
Explanation:
As it can be seen, all the corresponding elements of triplet C are greater than or equal to triplet B, and all the corresponding elements of triplet B are greater than or equal to triplet A.

Input: arr = {{1, 2, 3), {1, 2, 4}, {1, 3, 1}, {10, 20, 30}, {16, 9, 25}}
Output: Impossible

Approach: This problem can be solved using greedy approach. Keep all triplets with their triplet id in different lists and sort these lists of tuple in descending order. Follow the steps below to solve the problem.



  • Create three lists of tuples x, y, and z.
  • List x, y, z will keep triplets with their triplet id.
  • Sort x, on the basis of 1st element of the triplet.
  • Sort y, on the basis of the 2nd element of the triplet.
  • Sort z, on the basis of 3rd element of the triplet.
  • Iterate for i in range [0, N-1], check for all i, if x[i][3] = y[i][3] = z[i][3], then print the the respective order, otherwise print ‘Impossible’.

Below is the implementation of the above approach.

C++




//  C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
//  Function to find any possible order
vector<vector<int>> findOrder(vector<vector<int>> &A, vector<vector<int>> &x, vector<vector<int>> &y, vector<vector<int>> &z)
{
    int flag = 1;
 
    // Checking if there is any possible ordering
    for (int i = 0; i < x.size(); ++i)
    {
        if (x[i][3] == y[i][3] && y[i][3] == z[i][3])
            continue;
        else
        {
            flag = 0;
            break;
        }
    }
 
    vector<vector<int>> Order;
    if (flag)
    {
        for (int i = 0; i < x.size(); ++i)
            Order.push_back(A[x[i][3]]);
    }
 
    // Return Order
    return Order;
}
 
// Function to print order of triplets if
// Any possible
void PrintOrder(vector<vector<int>> &A)
{
 
    // Creating list of paired x, y and z.
    vector<vector<int>> x, y, z;
 
    for (int i = 0; i < A.size(); ++i)
    {
        x.push_back({A[i][0], A[i][1], A[i][2], i});
        y.push_back({A[i][1], A[i][0], A[i][2], i});
        z.push_back({A[i][2], A[i][0], A[i][1], i});
    }
 
    // Sorting of x, y and z
    sort(x.rbegin(), x.rend());
    sort(y.rbegin(), y.rend());
    sort(z.rbegin(), z.rend());
   
    // Function Call
    vector<vector<int>> order = findOrder(A, x, y, z);
 
    // Printing Order
    if (order.size() == 0)
        cout << "Impossible";
    else
    {
        for (auto v : order)
        {
            for (auto i : v)
                cout << i << " ";
            cout << "\n";
        }
    }
}
 
// Driver Code
int main()
{
 
    vector<vector<int>> A = {{4, 1, 1}, {3, 1, 1}, {2, 1, 1}};
     
    // Function Call
    PrintOrder(A);
    return 0;
}
 
// This code is contributed by rakeshsahni

Python3




# Python program for above approach
 
# Function to find any possible order
def findOrder(A, x, y, z):
  flag = 1
   
  # Checking if there is any possible ordering
  for i in range(len(x)):
    if x[i][3] == y[i][3] == z[i][3]:
      continue
    else:
      flag = 0
      break
   
  Order = 'Impossible'
  if flag:
    Order = []
    for i, j, k, l in x:
      Order += [A[l]]
     
  # Return Order  
  return Order
   
# Function to print order of triplets if
# Any possible
def PrintOrder(A):
   
  # Creating list of paired x, y and z.
  x, y, z = [], [], []
   
  for i in range(len(A)):
    x.append((A[i][0], A[i][1], A[i][2], i))
    y.append((A[i][1], A[i][0], A[i][2], i))
    z.append((A[i][2], A[i][0], A[i][1], i))
   
  # Sorting of x, y and z
  x.sort(reverse = True)
  y.sort(reverse = True)
  z.sort(reverse = True)
     
  # Function Call
  order = findOrder(A, x, y, z)
   
  # Printing Order
  print(order)
         
 
# Driver Code
A = [[4, 1, 1], [3, 1, 1], [2, 1, 1]]
 
# Function Call
PrintOrder(A)

Javascript




<script>
    //  Javascript program for above approach
    //  Function to find any possible order
    const findOrder = (A, x, y, z) => {
        let flag = 1;
 
        // Checking if there is any possible ordering
        for (let i = 0; i < x.length; ++i) {
            let index_x = JSON.stringify(x[i]);
            let index_y = JSON.stringify(y[i]);
            let index_z = JSON.stringify(z[i]);
            // index_x = [[4,1,1,0]] as string
            // we have to find 0 mean index_x[8]
 
            if (index_x[8] == index_y[8] && index_y[8] == index_z[8])
                continue;
            else {
                flag = 0;
                break;
            }
        }
 
        let Order = [];
        if (flag) {
            for (let itm in x) {
                let index_x = JSON.stringify(x[itm]);
                Order.push(A[index_x[8] - '0']);
            }
        }
 
        // Return Order
        return Order;
    }
 
    // Function to print order of triplets if
    // Any possible
    const PrintOrder = (A) => {
 
        // Creating list of paired x, y and z.
        let x = [];
        let y = [];
        let z = [];
 
        for (let i = 0; i < A.length; ++i) {
            x.push([[A[i][0], A[i][1], A[i][2], i]]);
            y.push([[A[i][1], A[i][0], A[i][2], i]]);
            z.push([[A[i][2], A[i][0], A[i][1], i]]);
        }
 
        // Sorting of x, y and z
        x.sort((a, b) => a - b)
        y.sort((a, b) => a - b)
        z.sort((a, b) => a - b)
        // Function Call
        let order = findOrder(A, x, y, z);
 
        // Printing Order
        if (order.length === 0) document.write("Impossible");
        else document.write(order);
 
    }
    // Driver Code
 
    const A = [[4, 1, 1], [3, 1, 1], [2, 1, 1]];
 
    // Function Call
    PrintOrder(A);
 
// This code is contributed by rakeshsahni
 
</script>
Output: 
[[4, 1, 1], [3, 1, 1], [2, 1, 1]]

 

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

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :