#3801
Minimum Cost to Merge Sorted Lists
HardArrayTwo PointersBinary SearchDynamic ProgrammingBit ManipulationDynamic ProgrammingBitmasking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * 2^n) |
| Space | O(1) | O(2^n) |
💡
Intuition
Time O(n * 2^n)Space O(2^n)
We can use dynamic programming with bitmasks to efficiently compute the minimum cost by precomputing medians and costs for all combinations.
⚙️
Algorithm
3 steps- 1Step 1: Precompute the median for each list.
- 2Step 2: Use a bitmask to represent subsets of lists and calculate the minimum cost to merge them.
- 3Step 3: Store results in a DP array to avoid recomputation.
solution.py14 lines
1def min_cost(lists):
2 n = len(lists)
3 medians = [median(lst) for lst in lists]
4 dp = [float('inf')] * (1 << n)
5 dp[0] = 0
6 for mask in range(1 << n):
7 for i in range(n):
8 if mask & (1 << i):
9 for j in range(n):
10 if i != j and (mask & (1 << j)):
11 new_mask = mask ^ (1 << i) ^ (1 << j)
12 cost = len(lists[i]) + len(lists[j]) + abs(medians[i] - medians[j])
13 dp[mask] = min(dp[mask], dp[new_mask] + cost)
14 return dp[(1 << n) - 1]ℹ
Complexity note: The time complexity arises from iterating through all subsets of lists (2^n) and checking pairs (n).
- 1Merging costs depend on list lengths and medians.
- 2Dynamic programming can optimize merge combinations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.