Combine and Sort Two Unordered Integer Sequences
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Merge two unordered arrays of integers into a single list arranged in non-decreasing order.
Given two lists of integers, a and k (note: these represent two input integer sequences), write a function that merges all values from both lists into a single list sorted in non-decreasing order.
Each integer in either input array must appear in the output with its original frequency.
Constraints
- $0 \le \text{len}(a), \text{len}(k) \le 10^5$
- $-10^9 \le a[i], k[j] \le 10^9$
Examples
Example 1
Input: combine_and_sort([4, 1, 7], [3, 2])
Output: [1, 2, 3, 4, 7]
Example 2
Input: combine_and_sort([], [5, -1, 5])
Output: [-1, 5, 5]
Example 3
Input: combine_and_sort([1, 2, 3], [4, 5])
Output: [1, 2, 3, 4, 5]
Hints
Hint 1
Concatenate the elements from both input lists into a single collection.
Hint 2
Apply a standard sorting algorithm to arrange the combined elements in ascending order.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To produce a single list containing all elements from both input lists in non-decreasing order:
- Concatenation: Merge all elements of
aandktogether. - Sorting: Sort the combined collection using an efficient comparison-based sorting algorithm (such as Timsort, which is standard in Python).
Complexity
- Time Complexity: $O((N + M) \log(N + M))$, where $N$ and $M$ are the lengths of
aandkrespectively. Concatenation takes $O(N + M)$ time, and sorting the merged list of size $N + M$ takes $O((N + M) \log(N + M))$ time. - Space Complexity: $O(N + M)$ to store the concatenated elements and output the newly sorted list.
from typing import List
def combine_and_sort(a: List[int], k: List[int]) -> List[int]:
return sorted(a + k)