# Sort N triplets

Given a 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 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: ImpossibleApproach: 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 list 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 triplet.Sort y, on the basis of 2nd element of triplet.Sort z, on the basis of 3rd element of 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 above approach.Python3 def findOrder(A, x, y, z): flag = 1 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 def PrintOrder(A): 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)) x.sort(reverse = True) y.sort(reverse = True) z.sort(reverse = True) order = findOrder(A, x, y, z) print(order) A = [[4, 1, 1], [3, 1, 1], [2, 1, 1]] PrintOrder(A)Output:

[[4, 1, 1], [3, 1, 1], [2, 1, 1]]

Time Complexity: O(N)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.