KatInterview

Sort a Large Sequence Using Memory-Bounded Runs and a Heap

Heaps, Sorting & SearchAuto-graded · 23 test cases

Last 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 ValueError if chunk_size is less than 1.
  • Return an empty list when data is empty.

Constraints

  • 1 <= chunk_size <= 10^6
  • 0 <= 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.