Cheapest Full Merge and Matching-Sum Product Total
Heaps, Sorting & SearchAuto-graded · 19 test casesLast 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^51 <= values[i] <= 10^6goalis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two quantities are independent, so solve each separately and return them together.
Part 1: cheapest full merge
Every merge cost is a sum that later becomes an element again, so it gets paid again in every subsequent merge it takes part in. The merges form a binary tree whose leaves are the original values, and the total cost equals the sum of value * depth over the leaves. This is exactly the Huffman coding objective.
The greedy rule is to always merge the two smallest current elements. A min-heap supports this in O(log n) per step.
Why it is correct: In an optimal tree, if a smaller value x were shallower than a larger value y, swapping them changes the cost by (x - y)(depth_y - depth_x) < 0, which cannot hurt. So the two smallest values can be placed at the deepest level as siblings. Merging them into one leaf a + b reduces the problem to a smaller instance, and the original cost equals the reduced cost plus a + b. Induction finishes the argument.
With 0 or 1 elements there is nothing to merge, so the cost is 0.
Part 2: matching pairs
Build a frequency map. For each distinct value v with complement c = goal - v:
- If
cis absent, orv > c, skip (the pair is counted from the smaller side). - If
v < c: there arecount[v] * count[c]index pairs, each with productv * c. - If
v == c: there arecount * (count - 1) / 2index pairs, each with productv * v.
Each qualifying index pair is attributed to exactly one distinct value, so nothing is double counted.
Complexity
- Time: O(n log n) for the heap merges, O(n) for counting.
- Space: O(n).
Reference solution
import heapq
from collections import Counter
from typing import List
def merge_cost_and_pair_products(values: List[int], goal: int) -> List[int]:
merge_cost = 0
if len(values) > 1:
heap = list(values)
heapq.heapify(heap)
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
s = a + b
merge_cost += s
heapq.heappush(heap, s)
counts = Counter(values)
product_total = 0
for v, c in counts.items():
other = goal - v
if other not in counts or v > other:
continue
if v == other:
product_total += (c * (c - 1) // 2) * v * v
else:
product_total += c * counts[other] * v * other
return [merge_cost, product_total]