Maintained by Vikas Dulgunde, software engineer
You receive two input arrays, list1 and list2. Each one is already arranged so that values never decrease as you move from left to right, and either array may be empty.
Your job is to produce a single new array that holds every value from both inputs while preserving the same non-decreasing order. Duplicate values are allowed and must all appear in the result.
This is the array version of merging two sorted linked lists. Because both inputs are pre-sorted, you do not need a full sort. Walking the two arrays together and always taking the smaller front value is enough to build the answer in one pass.
Compare fronts and take the smaller each time. The two 1s come first, then 2 from list1, then 3 from list2, then both 4s. Equal values keep their relative order.
Both inputs are empty, so there is nothing to merge and the result is an empty array.
The smallest front alternates between the two arrays, so the merged output interleaves them into one sorted sequence.
Visible test cases
You do not need to sort from scratch. Both arrays are already sorted, so think about how to merge rather than how to order.
Keep one index into each array. At every step compare the two current front values and copy the smaller one into the result, then advance only that index.
When one array runs out, the other array's remaining tail is already sorted, so append the rest of it directly without any more comparisons.
Ignore that the inputs are sorted, join them into one array, and let a general sort fix the order.
Because both inputs are already sorted, repeatedly take the smaller of the two front elements to build the result in a single pass.