Minimum Total Cost to Merge Adjacent Log Shards

Last updated: November 29, 2026

Quick Overview

You have n log shards in a fixed order with sizes s[0..n-1]. Merging two adjacent shards costs the sum of their sizes and produces one shard of that combined size. Return the minimum total cost to merge all shards into one.

LinkedIn
Coding & Algorithms
Software Engineer
LinkedIn
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


You have n log shards in a fixed order with sizes s[0..n-1]. Merging two adjacent shards costs the sum of their sizes and produces one shard of that combined size. Return the minimum total cost to merge all shards into one.

LinkedIn runs huge compaction jobs over Kafka-fed logs, and this problem frames compaction order as interval DP. The interviewer checks that you reject the Huffman greedy (adjacency breaks it) and derive the O(n^3) interval recurrence with prefix sums.

What the Interviewer Expects
  • Explains why the greedy or Huffman approach fails when only adjacent merges are allowed
  • Defines dp[i][j] as the min cost to merge shards i through j
  • Uses prefix sums so the final merge cost of a range is O(1)
  • Iterates by increasing interval length
  • States O(n^3) time and mentions Knuth's optimization to O(n^2)
Key Topics to Cover
interval DP
prefix sums
Knuth optimization
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
  • How does Knuth's optimization reduce this to O(n^2) and why does it apply?
  • What if each merge combines exactly k adjacent shards?
  • What if shards could be merged in any order, not just adjacent ones?
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

Sizes are nonnegative integers. Order is fixed and only neighbors may merge. Cost of a merge is the combined size. One shard costs 0. Up to a few hundred shards, so O(n^3) is acceptable....

High-Level Design

Any merge plan for the range [i, j] ends with one final merge of a left block [i, m] and right block [m+1, j], and that final merge costs sum(i..j) regardless of m. So `dp[i][j] = min over m of dp[i...


Submit Your Answer
Markdown supported