Sort a Large Sequence Using Memory-Bounded Runs and a Heap
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Tests knowledge of two-phase external sorting: chunking a sequence into fixed-size sorted runs, then merging them efficiently with a min-heap.
Memory-Bounded Multi-Way Merge Sort
Imagine you are processing a sequence of integers that is too large to sort all at once. You are allowed to sort small chunks that fit in a fixed memory budget, write each sorted chunk to temporary storage, then stream the chunks back and merge them into one fully sorted output.
Your job is to simulate this two-phase process.
Phase 1 — Produce sorted runs
Read elements from data from left to right. Group them into consecutive windows of at most chunk_size elements. Sort each window in ascending order. These windows are your runs.
Phase 2 — Merge runs with a min-heap
All runs are sorted, so the next element in the global sorted order must be the current front element of one of the runs. Use a min-heap to track one candidate per run and repeatedly extract the minimum. When two candidates have equal values, the one belonging to the run with the smaller original index comes first (this keeps the merge deterministic).
What to implement
merge_sort_external(data, chunk_size) -> List[int]
data— a list of integers to sort.chunk_size— the maximum number of elements allowed in a single run.- Returns a fully sorted list containing every element of
data(duplicates preserved). - Raise
ValueErrorifchunk_sizeis less than 1. - Return an empty list when
datais empty.
Constraints
1 <= chunk_size <= 10^60 <= len(data) <= 10^6-10^9 <= data[i] <= 10^9- All duplicates must appear in the output.
- The input list must not be modified.
Examples
Example 1
Input: merge_sort_external([7, 1, 5, 2, 9, 3, 4], 3)
Output: [1, 2, 3, 4, 5, 7, 9]
Example 2
Input: merge_sort_external([5, -2, 5, -2], 2)
Output: [-2, -2, 5, 5]
Example 3
Input: merge_sort_external([4, 3, 2, 1], 10)
Output: [1, 2, 3, 4]
Hints
Hint 1
Split the input into slices of length chunk_size, sort each slice, and store the slices as your runs — this is the entire first phase.
Hint 2
For the merge, push a tuple of (value, run_index, position_within_run) onto a min-heap — one entry per run. The run_index as a tie-breaker ensures Python never tries to compare two integers that are equal by falling through to an unsupported comparison.
Hint 3
Each time you pop an entry, append its value to the result and, if the same run still has elements left, push the next element from that run. The heap never holds more than one entry per run.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The algorithm has two self-contained phases.
Phase 1 — Run generation
Slice data into consecutive windows of length chunk_size (the last window may be shorter). Sort each window in place, then store it. Slicing copies the data, so the caller's list is never mutated. After this phase you have K = ceil(N / chunk_size) sorted lists called runs.
Phase 2 — K-way merge
Because every run is sorted, the globally smallest not-yet-emitted element must be the front element of some run. A min-heap holding one cursor per run always surfaces that element in O(log K).
Each heap entry is a three-tuple (value, run_index, position):
value— the integer being compared.run_index— the zero-based index of the run this element came from. This acts as a stable tie-breaker: when two runs hold the same value, the one with the lower index wins. Without this field, Python would fall through to comparing the third element, which works numerically but obscures intent; in a variant that stores iterators the comparison would raiseTypeError.position— the cursor into the run, used to find the successor element.
The loop pops the minimum, appends it to the result, then pushes the next element from the same run (if one exists). The heap therefore never holds more than one entry per run, and its size never exceeds K.
Why it is correct
Invariant: before each pop, the heap contains exactly the smallest remaining element of every non-exhausted run.
- On initialization,
run[0]is each run's minimum, so the invariant holds. - After popping
(v, r, p)and pushingruns[r][p+1], runr's new minimum is in the heap. No other run changed. The invariant is maintained. - Because every remaining element is
>=its run's current head, and every head is>=the heap minimum, the popped value is<=everything still in the heap or in any run. Emissions are non-decreasing. - Every element is pushed exactly once (either at initialization or when its predecessor is popped) and popped exactly once, so all
Nelements are emitted.
Edge cases
chunk_size < 1— raiseValueErrorimmediately.- Empty input — no runs are created; return
[]before the heap is built. chunk_size >= N— a single run is produced; the merge simply walks it.chunk_size == 1—Nsingle-element runs; the merge degenerates to heapsort. Still correct and stillO(N log N).- All duplicates — the
run_indextie-breaker keeps tuple comparisons unambiguous.
Complexity
Let N = len(data), R = chunk_size, and K = ceil(N / R).
- Phase 1:
Ksorts of length<= R→O(N log R). - Phase 2:
Npops and up toNpushes on a heap of size<= K→O(N log K). - Total time:
O(N log R + N log K) = O(N log N). - Space:
O(N)for the runs and output in this in-memory simulation;O(K)for the heap. In a true external sort the runs live on disk, so memory isO(R + K).
Reference solution
import heapq
from typing import List
def merge_sort_external(data: List[int], chunk_size: int) -> List[int]:
if chunk_size < 1:
raise ValueError("chunk_size must be at least 1")
# Phase 1: build sorted runs of length <= chunk_size.
runs = []
for start in range(0, len(data), chunk_size):
run = data[start:start + chunk_size] # slice copies; input untouched
run.sort()
runs.append(run)
if not runs:
return []
# Phase 2: K-way merge via min-heap.
# Heap entries: (value, run_index, position)
# run_index breaks ties between equal values deterministically.
heap = []
for run_index, run in enumerate(runs):
heapq.heappush(heap, (run[0], run_index, 0))
result = []
while heap:
value, run_index, position = heapq.heappop(heap)
result.append(value)
next_position = position + 1
if next_position < len(runs[run_index]):
heapq.heappush(
heap,
(runs[run_index][next_position], run_index, next_position),
)
return result