Cheapest Way to Merge Sorted Log Segments Pairwise

Last updated: November 29, 2026

Quick Overview

You have log segments of given lengths. Merging two segments costs the sum of their lengths and yields one segment of that combined length. Return the minimum total cost to merge all segments into one.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Easy

0

0

0 solved


You have log segments of given lengths. Merging two segments costs the sum of their lengths and yields one segment of that combined length. Return the minimum total cost to merge all segments into one.

Shows up in Google screens as a compaction question for a log-structured store such as Bigtable SSTables. The interviewer checks the Huffman-style greedy and wants a short argument for why always merging the two smallest is optimal.

What the Interviewer Expects
  • Chooses the greedy of merging the two smallest
  • Gives an exchange-argument proof sketch
  • Uses a min-heap
  • States O(n log n) time
  • Handles zero or one segment
Key Topics to Cover
Min-Heap
Greedy
Huffman Coding
Compaction
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if you can merge up to three segments at once?
  • What if only adjacent segments may be merged?
  • How does this relate to Huffman coding?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: list of positive integer lengths.
  • Each merge of lengths a and b costs a + b and produces a segment of length a + b.
  • Return the minimum total cost; 0 if there are fewer than two segments. ...
High-Level Design

Every original segment is paid for once per merge it participates in, so its total contribution is its length times its depth in the merge tree. To minimize the weighted depth sum, the smallest segmen...


Submit Your Answer
Markdown supported