KatInterview

Stable Divide-and-Conquer Sort of an Integer List

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingdivide-and-conquermerge-sort

Last updated

Sort a list of integers in ascending order without mutating the input, using a divide-and-conquer merge approach that guarantees O(n log n) time and linear auxiliary space.

Sort by Merging

Write a function that takes a list of integers and returns a new list containing the same values arranged from smallest to largest (non-decreasing order).

The intent is for you to build the sort yourself using a divide-and-conquer strategy, where sorted pieces are combined by merging, rather than relying on a built-in sort. Your approach should:

  • run in O(n log n) time for every input, including already ordered, reverse ordered, and all-equal inputs;
  • be stable: when two values are equal, the one that appeared earlier in the input must appear earlier in the output;
  • use O(n) auxiliary space.

The input list must not be modified. Return a fresh list, even when the input is empty or has a single element.

Input

  • values: a list of integers.

Output

  • A new list with the elements of values sorted in non-decreasing order.

Edge cases

  • An empty list returns an empty list.
  • A single-element list returns a list with that element.
  • Lists with all identical elements, or lists that are already sorted or sorted in reverse, must still be handled correctly.

Constraints

  • 0 <= len(values) <= 10^5
  • -10^9 <= values[i] <= 10^9
  • Target O(n log n) time and O(n) auxiliary space.

Examples

Example 1

Input: stable_merge_sort([38, 27, 43, 3, 9, 82, 10])

Output: [3, 9, 10, 27, 38, 43, 82]

Example 2

Input: stable_merge_sort([5, 2, 5, 1])

Output: [1, 2, 5, 5]

Hints

Hint 1

Think of the list as many tiny sorted runs. A run of length 1 is already sorted, so the real work is combining two sorted runs into one.

Hint 2

To merge two sorted runs, keep one pointer at the front of each and repeatedly take the smaller front element. When the fronts are equal, take from the left run so equal elements keep their original order. Then append whatever is left in the other run.

Hint 3

You can recurse by splitting in halves, or iterate bottom-up by merging runs of width 1, 2, 4, and so on. In the iterative version, alternate between two buffers so you only allocate one extra array.