1367. Fan-In Merge Cost

Hard7.5 points estimatedGreedyHeapMerge SortArray

A database engine has written several sorted files to disk. The array runs gives the number of rows in each file. One merge step reads between 2 and fanIn files at once and writes them out as a single sorted file, and the step costs as much as the total number of rows it handles.

Return the minimum total cost of merge steps that end with exactly one file, as a long; one file needs no step, so the cost is 0. The optimal plan is a fanIn-ary Huffman merge: first add empty files (length 0) until the file count c satisfies (c - 1) % (fanIn - 1) == 0, then repeatedly merge the fanIn smallest files. Aim for O(n log n) time and O(n) space.

Example 1

Input:
runs = [1,2,3,4], fanIn = 2
Output:
19
Explanation:

Merge 1 and 2 (cost 3), then 3 and 3 (cost 6), then 4 and 6 (cost 10), for a total of 19.

Example 2

Input:
runs = [5,5,5], fanIn = 3
Output:
15
Explanation:

One step merges all three files at once and handles 15 rows, so the cost is 15.

Example 3

Input:
runs = [9], fanIn = 4
Output:
0
Explanation:

A single file is already the final file, so no merge step is needed.

Constraints

  • 1 ≤ runs.length ≤ 105

  • 2 ≤ fanIn ≤ 105

  • 1 ≤ runs[i] ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…