KatInterview

Cheapest Full Merge and Matching-Sum Product Total

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapgreedyhash-map

Last updated

Combine a Huffman-style min-heap greedy for the cheapest full merge with a frequency-map count of index pairs hitting a target sum, summing their products.

You are given a list of positive integers values and an integer goal. Compute two independent quantities and return them together as a list [merge_cost, product_total].

Quantity 1: Cheapest full merge

In one step you choose any two elements of the current list, remove them, and insert their sum. That step costs the value of the sum. Repeat until a single element remains. merge_cost is the smallest possible total cost over all ways of performing the merges.

If the list has zero or one element, no steps are needed and merge_cost is 0.

Quantity 2: Product total over matching pairs

Consider every pair of positions i < j in values such that values[i] + values[j] == goal. Each such pair of positions counts once, so repeated values produce multiple pairs. product_total is the sum of values[i] * values[j] over all these pairs.

If no pair matches (including when the list is empty or has a single element), product_total is 0.

Output

Return [merge_cost, product_total].

For instance, with values = [3, 3, 3] and goal = 6, there are three matching position pairs, each with product 9, so product_total is 27.

Constraints

  • 0 <= len(values) <= 10^5
  • 1 <= values[i] <= 10^6
  • goal is an integer
  • Results can be large; use arbitrary precision integers (Python ints are fine).

Examples

Example 1

Input: merge_cost_and_pair_products([1, 2, 3], 6)

Output: [9, 0]

Example 2

Input: merge_cost_and_pair_products([1, 5, 3, 3], 6)

Output: [23, 14]

Example 3

Input: merge_cost_and_pair_products([], 10)

Output: [0, 0]

Example 4

Input: merge_cost_and_pair_products([7], 14)

Output: [0, 0]

Hints

Hint 1

Think about which two elements should be merged first: a sum is paid again every time it is merged later, so large values should be merged as late as possible.

Hint 2

A min-heap lets you repeatedly take the two smallest current elements, merge them, push the sum back, and accumulate its cost.

Hint 3

For the pair part, build a frequency map. For each distinct value v with complement goal - v, only process v <= complement to avoid double counting; use count_v * count_c for v < complement and count*(count-1)/2 when v equals its complement.