The merge(a, b)
function merges two sorted lists a
and b
in descending order into a single list, with a time complexity of O(n log n). It does this using a list comprehension that pops the largest element from either list at each iteration, as implemented by return [max(a, b).pop(0) for _ in a+b]
.
def merge(a, b):
"""Merge two lists sorted in descending order."""
return [max(a, b).pop(0) for _ in a+b]
assert merge([], []) == []
assert merge([1], [0]) == [1,0]
assert merge([7,5,1], [2]) == [7,5,2,1]
print('All passed!')
python
def merge_sorted_descending(list1, list2):
"""
Merge two lists sorted in descending order into a new sorted list.
Args:
list1 (list): The first list to merge.
list2 (list): The second list to merge.
Returns:
list: A new list containing all elements from both input lists, sorted in descending order.
Raises:
ValueError: If either input list is not sorted in descending order.
"""
# Check if input lists are sorted in descending order
if not all(x >= y for x, y in zip(list1, list1[1:] + [0])) or \
not all(x >= y for x, y in zip(list2, list2[1:] + [0])):
raise ValueError("Input lists must be sorted in descending order.")
# Merge the lists using a two-pointer technique
result = []
i, j = 0, 0
# Compare elements from both lists and add the larger one to the result
while i < len(list1) and j < len(list2):
if list1[i] >= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
# Add any remaining elements from the first list
while i < len(list1):
result.append(list1[i])
i += 1
# Add any remaining elements from the second list
while j < len(list2):
result.append(list2[j])
j += 1
return result
assert merge_sorted_descending([], []) == []
assert merge_sorted_descending([1], [0]) == [1, 0]
assert merge_sorted_descending([7, 5, 1], [2]) == [7, 5, 2, 1]
print('All passed!')
merge(a, b)
Merge two lists a
and b
, each sorted in descending order, into a single list.
a
(list): First list to merge, sorted in descending order.b
(list): Second list to merge, sorted in descending order.A new list containing the merged elements in descending order.
return [max(a, b).pop(0) for _ in a+b]
This implementation uses a list comprehension to create a new list by popping the largest element from either a
or b
(determined by max(a, b)
) at each iteration.
merge([], [])
: Returns an empty list.merge([1], [0])
: Returns [1, 0]
.merge([7, 5, 1], [2])
: Returns [7, 5, 2, 1]
.This implementation has a time complexity of O(n log n) due to the use of max(a, b)
which has to iterate over both lists. A more efficient implementation could use a two-pointer technique to iterate over both lists simultaneously.