Skip to main content
Beginnercoding Verified

Implement merge sort, analyse its time complexity, and discuss its edge cases.

ReportedSource: GeeksforGeeks interview experience: Apple SDE on-campus 2024

Quick answer

Split in halves, sort recursively, merge with <= for stability. O(n log n) in all cases, O(n) extra space. Good for stability, linked lists and external sorting.

Constraints

  • Input: first line n, second line n integers (the second line is empty when n is 0).
  • 0 <= n <= 100000, values between -10^9 and 10^9, duplicates allowed.
  • Output: the sorted numbers on one line separated by single spaces (an empty line when n is 0).
  • Implement merge sort yourself; do not call the built-in sort.

Sample I/O

in: 6 5 2 4 7 1 3

out: 1 2 3 4 5 7

in: 1 42

out: 42

in: 5 3 3 1 1 2

out: 1 1 2 3 3

Loading editor…
Output

Sign up to run your code in the sandbox.

Sign up to run code and get an AI review

You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.

Sign up free

Hints

Reference solution

Divide and conquer. Split the array in half, sort each half recursively, then merge the two sorted halves.

main.py
def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:     # <= keeps it stable
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    out.extend(left[i:]); out.extend(right[j:])
    return out

Complexity. Recurrence T(n) = 2T(n/2) + O(n), so O(n log n) in best, average and worst case. Space O(n) for the merge buffer plus O(log n) recursion.

Edge cases. Empty and single-element arrays; duplicates (use <= for stability); already sorted input (still n log n, unlike quicksort's worst case being avoided here); odd lengths.

When to choose it. Stable sort, guaranteed n log n, linked lists (merging needs no extra array), and external sorting of data larger than memory.

Discussion