Related Articles

# Sort N triplets

• Last Updated : 24 Oct, 2021

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] = y[i] = z[i], then print the the respective order, otherwise print ‘Impossible’.

Below is the implementation of the above approach.

## C++

 `//  C++ program for above approach``#include ``using` `namespace` `std;` `//  Function to find any possible order``vector> findOrder(vector> &A, vector> &x, vector> &y, vector> &z)``{``    ``int` `flag = 1;` `    ``// Checking if there is any possible ordering``    ``for` `(``int` `i = 0; i < x.size(); ++i)``    ``{``        ``if` `(x[i] == y[i] && y[i] == z[i])``            ``continue``;``        ``else``        ``{``            ``flag = 0;``            ``break``;``        ``}``    ``}` `    ``vector> Order;``    ``if` `(flag)``    ``{``        ``for` `(``int` `i = 0; i < x.size(); ++i)``            ``Order.push_back(A[x[i]]);``    ``}` `    ``// Return Order``    ``return` `Order;``}` `// Function to print order of triplets if``// Any possible``void` `PrintOrder(vector> &A)``{` `    ``// Creating list of paired x, y and z.``    ``vector> x, y, z;` `    ``for` `(``int` `i = 0; i < A.size(); ++i)``    ``{``        ``x.push_back({A[i], A[i], A[i], i});``        ``y.push_back({A[i], A[i], A[i], i});``        ``z.push_back({A[i], A[i], A[i], 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> 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> 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

 ``
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