Minimum Cost to Merge Adjacent Review Index Shards

Last updated: November 29, 2026

Quick Overview

A review search index is stored as a row of time ordered shards with known sizes; merging two adjacent shards costs the sum of their sizes and produces one shard. Return the minimum total cost to merge all shards into one.

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

0

0

0 solved


A review search index is stored as a row of time ordered shards with known sizes; merging two adjacent shards costs the sum of their sizes and produces one shard. Return the minimum total cost to merge all shards into one.

Search over Yelp's review corpus relies on segment merging similar to Lucene and Elasticsearch, and keeping time order means only neighbors can merge. Unlike the Huffman style greedy, adjacency makes this an interval DP, and the interviewer checks whether you notice greedy fails and can define the recurrence.

What the Interviewer Expects
  • Show that merging the two smallest adjacent shards greedily is not optimal in general
  • Define dp[i][j] as the min cost to merge shards i through j
  • Use prefix sums so the final merge cost is O(1)
  • Fill the table by increasing interval length
  • Mention Knuth's optimization or Garsia Wachs for large n
Key Topics to Cover
interval DP
prefix sums
optimal substructure
2D dynamic programming
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 any two shards can merge, not just adjacent ones?
  • What if each merge combines exactly k adjacent shards?
  • How would you also return the merge order?
  • How does this relate to how real search engines schedule segment merges?
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 integers sizes. Each merge picks two neighbors and replaces them with one shard of the combined size, paying that size (it reads and rewrites all those bytes). Output: minima...

High-Level Design

Look at the last merge for shards i..j. It joins a left block i..m and a right block m+1..j, each already fully merged, and pays sum(i..j) no matter where m is. So `dp[i][j] = min over m of dp[i][m]...


Submit Your Answer
Markdown supported

Related Questions