DryRun
AlgorithmsCourseCompare
DryRun
AlgorithmsCourseCompareGitHubLinkedIn

© 2026 DryRun. Built by Aditya Pandey.

AlgorithmsGreedyOptimal Merge Patterns
Greedyintermediategreedyheapmerge-cost

Optimal Merge Patterns

Given sorted file lengths, always merge the two smallest first (min-heap strategy). This greedy method minimizes total weighted merge cost and is analogous to Huffman coding construction.

Complexity

Best
O(n log n)
Average
O(n log n)
Worst
O(n log n)
Space
O(n)

Implementation

int optimalMerge(vector<int>& files) {
    priority_queue<int, vector<int>, greater<int>> pq(files.begin(), files.end());
    int cost = 0;
    while (pq.size() > 1) {
        int a = pq.top(); pq.pop();
        int b = pq.top(); pq.pop();
        int c = a + b;
        cost += c;
        pq.push(c);
    }
    return cost;
}

How It Works

1.Greedy Rule

Merge the two smallest files first at each step.

2.Heap Implementation

Min-heap provides efficient repeated extraction of smallest elements.

3.Relation to Huffman

Same structural idea as building optimal prefix-code trees.

Related Algorithms

TrendingUpHuffman EncodingTrendingUpFractional Knapsack

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms