![]() |
VOOZH | about |
Given a list of dual tuples, the task here is to write a Python program that can sort them by the frequency of their elements' absolute differences.
Input : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)] Output : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)] Explanation : 7 - 5 = 2 occurs only 1 time. 5 occurs twice [( 6 - 1), (11 - 6)] and 8 occurs 3 times as difference.
Input : [(1, 6), (6, 11), (5, 7)] Output : [(5, 7), (1, 6), (6, 11)] Explanation : 7 - 5 = 2 occurs only 1 time. 5 occurs twice [( 6 - 1), (11 - 6)].
Method 1: Using sorted(), abs(), count() and list comprehension
In this, we perform the task of computing each absolute difference using abs() and list comprehension. Then, sorted() and count() are used to sort tuples based on computed results of absolute difference.
Output:
The original list is : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)]
Sorted Tuples : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)]
Time Complexity: O(n*logn)
Auxiliary Space: O(1)
Method 2: operator.countOf() and list comprehension
The original list is : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)] Sorted Tuples : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)]
Time Complexity: O(NLogN), where n is the length of the given string
Auxiliary Space: O(N)
Method 3: Using the map() function and a lambda function
Step-by-step approach:
The original list is : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)] Sorted Tuples : [(5, 7), (1, 6), (6, 11), (11, 3), (9, 1), (2, 10)]
Time complexity: O(nlogn), where n is the length of the list of tuples since sorting takes O(nlogn) time.
Auxiliary space: O(n), since we create a list of absolute differences that is the same length as the list of tuples
Method 4: Using the heapq module
The original list is : [(1, 6), (11, 3), (9, 1), (6, 11), (2, 10), (5, 7)] Sorted Tuples : [(5, 7), (1, 6), (6, 11), (2, 10), (9, 1), (11, 3)]
Time complexity: O(n log n)
Auxiliary space: O(n)