1. Out-of-Place List Merging (Brute Force)
Intuition
Divide the array into two halves until length <= 1. Recursively sort each half, then merge the two sorted halves into a newly allocated output array.
When to apply: Use to understand divide-and-conquer before optimizing memory allocations.
Recursive Divide & Conquer Trace
2 of 2 questions left todayArray: [38, 27, 43, 3, 9, 82, 10]
Array: [38, 27, 43, 3, 9, 82, 10]. Split at mid=3 into left [38, 27, 43] and right [3, 9, 82, 10].
import java.util.*; public class Main { public static class Solution { public int[] sortArray(int[] nums) { if (nums.length <= 1) return nums; int mid = nums.length / 2; int[] left = sortArray(Arrays.copyOfRange(nums, 0, mid)); int[] right = sortArray(Arrays.copyOfRange(nums, mid, nums.length)); int[] res = new int[nums.length]; int i = 0, j = 0, k = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) res[k++] = left[i++]; else res[k++] = right[j++]; } while (i < left.length) res[k++] = left[i++]; while (j < right.length) res[k++] = right[j++]; return res; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {38, 27, 43, 3, 9, 82, 10}; System.out.println("Sorted: " + Arrays.toString(sol.sortArray(nums))); }}Time & Space Complexity
- Time complexity:
O(n log n)— n elements at each of log n levels of recursion. - Space complexity:
O(n log n)— Repeated subarray allocations across the call tree.
Why Brute Force Doesn't Scale:
Allocating small temporary vectors at every recursion node triggers millions of malloc/free cycles. A single pre-allocated auxiliary buffer reduces memory allocations from O(N) down to 1.
For N = 10,000,000 integers, naive slicing allocates ~100MB across ~20M tiny objects, triggering massive GC pauses. Pre-allocated buffer allocates exactly one 40MB array upfront.