Full answer
Problem
Sort a list of comparable values and return a new sorted list, keeping the input unchanged.
Example: [38, 27, 43, 3, 9, 82, 10] gives [3, 9, 10, 27, 38, 43, 82].
Constraints: 0 <= n <= 10^5; values may repeat; the sort must be stable (equal values keep their input order).
Brute force
Selection or insertion sort: O(n^2) comparisons, about 5 x 10^9 for n = 10^5.
Optimal approach
- Base case: lists of length 0 or 1 are sorted.
- Split at
mid = len(nums) // 2; sort both halves recursively. - Merge: two indices
iandj; appendleft[i]ifleft[i] <= right[j], otherwiseright[j]; then append whatever remains.
Why it works
Correctness: the merge always takes the smallest remaining element, because each half is sorted and the smallest remaining element of a half is at its front.
Running time: the recursion tree has about log2(n) levels. On each level, the merges together touch every element once, so each level costs O(n). Total O(n log n), the same for best, average and worst cases.
Stability: on ties the merge takes from the left half, which holds elements that came earlier in the input, so equal elements never swap order. Using < instead of <= would break stability.
Complexity
O(n log n) time in all cases. O(n) extra space for the merged lists, plus O(log n) recursion depth.
Code
def merge_sort(nums):
"""Stable merge sort returning a new list. O(n log n) time, O(n) extra space."""
if len(nums) <= 1:
return list(nums)
mid = len(nums) // 2
left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:])
return merge(left, right)
def merge(left, right):
out = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= takes from the left on ties: stable
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
if __name__ == "__main__":
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([5, 5, 1, 5]) == [1, 5, 5, 5]
assert merge_sort([3, -1, 0, -1]) == [-1, -1, 0, 3]
data = [9, 1, 8, 2]
assert merge_sort(data) == [1, 2, 8, 9] and data == [9, 1, 8, 2] # input unchanged
print("all tests passed")Save as a43_merge_sort.py and run python3 a43_merge_sort.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty list and single element. All equal values. Negative numbers. The input list is not modified (the test checks this). Very large lists work because recursion depth is only about log2(n), around 17 for 10^5.
Pattern
Divide and conquer: split, solve halves, combine. The merge step is reused in counting inversions, merging k sorted lists and external sorting. Python's built-in sorted uses Timsort, a stable hybrid of merge sort and insertion sort.
def merge_sort(nums):
"""Stable merge sort returning a new list. O(n log n) time, O(n) extra space."""
if len(nums) <= 1:
return list(nums)
mid = len(nums) // 2
left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:])
return merge(left, right)
def merge(left, right):
out = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= takes from the left on ties: stable
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
if __name__ == "__main__":
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([5, 5, 1, 5]) == [1, 5, 5, 5]
assert merge_sort([3, -1, 0, -1]) == [-1, -1, 0, 3]
data = [9, 1, 8, 2]
assert merge_sort(data) == [1, 2, 8, 9] and data == [9, 1, 8, 2] # input unchanged
print("all tests passed")Recursive merge sort returning a new list; ties take from the left half to stay stable.
Complexity
Time: O(n log n) in all cases. Space: O(n) extra plus O(log n) recursion. Python's built-in sorted uses Timsort, a stable merge-based hybrid.
By level
Fresher: Implements merge sort with the merge helper and explains the levels-times-work argument. Should test an empty list and equal values.
Mid: Explains stability with ties, compares with quicksort and mentions inversion counting. Explains why < in the merge breaks stability.
Senior: Discusses Timsort, external merge sort for disk data, bottom-up iterative merge sort and parallel merging. Explains why Python uses Timsort.
Key points
- Split, sort halves, merge
- log n levels with O(n) work each
- Same time in best, average and worst cases
- <= in the merge keeps it stable
- O(n) extra space
Common mistakes
- Using < in the merge and losing stability
- Forgetting to append the leftover elements
- Slicing in a way that loses or repeats an element
- Claiming it sorts in place with O(1) space
Follow-ups
- How would you count inversions using merge sort?
- How would you sort a linked list in O(n log n)?
- Why does Python use Timsort?
Tips
- Draw the recursion tree to explain log n levels
- Show a tie to explain stability
- Mention space cost
Evaluation rubric
- Correct implementation
- Correct complexity argument
- Explains stability correctly
- Handles edge cases