LeetCode #3801 — HARD

Minimum Cost to Merge Sorted Lists

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given a 2D integer array lists, where each lists[i] is a non-empty array of integers sorted in non-decreasing order.

You may repeatedly choose two lists a = lists[i] and b = lists[j], where i != j, and merge them. The cost to merge a and b is:

len(a) + len(b) + abs(median(a) - median(b)), where len and median denote the list length and median, respectively.

After merging a and b, remove both a and b from lists and insert the new merged sorted list in any position. Repeat merges until only one list remains.

Return an integer denoting the minimum total cost required to merge all lists into one single sorted list.

The median of an array is the middle element after sorting it in non-decreasing order. If the array has an even number of elements, the median is the left middle element.

Example 1:

Input: lists = [[1,3,5],[2,4],[6,7,8]]

Output: 18

Explanation:

Merge a = [1, 3, 5] and b = [2, 4]:

  • len(a) = 3 and len(b) = 2
  • median(a) = 3 and median(b) = 2
  • cost = len(a) + len(b) + abs(median(a) - median(b)) = 3 + 2 + abs(3 - 2) = 6

So lists becomes [[1, 2, 3, 4, 5], [6, 7, 8]].

Merge a = [1, 2, 3, 4, 5] and b = [6, 7, 8]:

  • len(a) = 5 and len(b) = 3
  • median(a) = 3 and median(b) = 7
  • cost = len(a) + len(b) + abs(median(a) - median(b)) = 5 + 3 + abs(3 - 7) = 12

So lists becomes [[1, 2, 3, 4, 5, 6, 7, 8]], and total cost is 6 + 12 = 18.

Example 2:

Input: lists = [[1,1,5],[1,4,7,8]]

Output: 10

Explanation:

Merge a = [1, 1, 5] and b = [1, 4, 7, 8]:

  • len(a) = 3 and len(b) = 4
  • median(a) = 1 and median(b) = 4
  • cost = len(a) + len(b) + abs(median(a) - median(b)) = 3 + 4 + abs(1 - 4) = 10

So lists becomes [[1, 1, 1, 4, 5, 7, 8]], and total cost is 10.

Example 3:

Input: lists = [[1],[3]]

Output: 4

Explanation:

Merge a = [1] and b = [3]:

  • len(a) = 1 and len(b) = 1
  • median(a) = 1 and median(b) = 3
  • cost = len(a) + len(b) + abs(median(a) - median(b)) = 1 + 1 + abs(1 - 3) = 4

So lists becomes [[1, 3]], and total cost is 4.

Example 4:

Input: lists = [[1],[1]]

Output: 2

Explanation:

The total cost is len(a) + len(b) + abs(median(a) - median(b)) = 1 + 1 + abs(1 - 1) = 2.

Constraints:

  • 2 <= lists.length <= 12
  • 1 <= lists[i].length <= 500
  • -109 <= lists[i][j] <= 109
  • lists[i] is sorted in non-decreasing order.
  • The sum of lists[i].length will not exceed 2000.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given a 2D integer array lists, where each lists[i] is a non-empty array of integers sorted in non-decreasing order. You may repeatedly choose two lists a = lists[i] and b = lists[j], where i != j, and merge them. The cost to merge a and b is: len(a) + len(b) + abs(median(a) - median(b)), where len and median denote the list length and median, respectively. After merging a and b, remove both a and b from lists and insert the new merged sorted list in any position. Repeat merges until only one list remains. Return an integer denoting the minimum total cost required to merge all lists into one single sorted list. The median of an array is the middle element after sorting it in non-decreasing order. If the array has an even number of elements, the median is the left middle element.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Two Pointers · Binary Search · Dynamic Programming · Bit Manipulation

Example 1

[[1,3,5],[2,4],[6,7,8]]

Example 2

[[1,1,5],[1,4,7,8]]

Example 3

[[1],[3]]
Step 02

Core Insight

What unlocks the optimal approach

  • Use dynamic programming and bitmasks
  • Precompute the medians for every mask
  • Let <code>dp[mask]</code> represent the minimum cost to merge all lists in <code>mask</code>
  • <code>dp[mask] = min(dp[s] + dp[mask ^ s] + cost(s, mask ^ s))</code>, where <code>s</code> and <code>mask ^ s</code> are nonempty disjoint submasks whose union is <code>mask</code>
  • Use the precomputed medians to compute costs efficiently
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3801: Minimum Cost to Merge Sorted Lists
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3801: Minimum Cost to Merge Sorted Lists
// package main
// 
// import (
// 	"math"
// 	"math/bits"
// 	"sort"
// )
// 
// // https://space.bilibili.com/206214
// func minMergeCost1(lists [][]int) int64 {
// 	u := 1 << len(lists)
// 	sorted := make([][]int, u)
// 	for i, a := range lists { // 枚举不在 s 中的下标 i
// 		highBit := 1 << i
// 		for s, b := range sorted[:highBit] {
// 			sorted[highBit|s] = merge(a, b)
// 		}
// 	}
// 
// 	f := make([]int, u)
// 	for i, a := range sorted {
// 		if i&(i-1) == 0 { // i 只包含一个元素,无法分解成两个非空子集
// 			continue // f[i] = 0
// 		}
// 		f[i] = math.MaxInt
// 		// 枚举 i 的非空真子集 j
// 		for j := i & (i - 1); j > i^j; j = (j - 1) & i {
// 			k := i ^ j // j 关于 i 的补集是 k
// 			medJ := sorted[j][(len(sorted[j])-1)/2]
// 			medK := sorted[k][(len(sorted[k])-1)/2]
// 			f[i] = min(f[i], f[j]+f[k]+abs(medJ-medK))
// 		}
// 		f[i] += len(a)
// 	}
// 	return int64(f[u-1])
// }
// 
// func minMergeCost2(lists [][]int) int64 {
// 	u := 1 << len(lists)
// 	sumLen := make([]int, u)
// 	for i, a := range lists {
// 		highBit := 1 << i
// 		for s, sl := range sumLen[:highBit] {
// 			sumLen[highBit|s] = sl + len(a)
// 		}
// 	}
// 
// 	median := make([]int, u)
// 	for mask, sl := range sumLen {
// 		k := (sl + 1) / 2
// 		left, right := int(-1e9), int(1e9)
// 		median[mask] = left + sort.Search(right-left, func(med int) bool {
// 			med += left
// 			cnt := 0
// 			for s := uint32(mask); s > 0; s &= s - 1 {
// 				i := bits.TrailingZeros32(s)
// 				cnt += sort.SearchInts(lists[i], med+1)
// 				if cnt >= k {
// 					return true
// 				}
// 			}
// 			return false
// 		})
// 	}
// 
// 	f := make([]int, u)
// 	for i, sl := range sumLen {
// 		if i&(i-1) == 0 {
// 			continue
// 		}
// 		f[i] = math.MaxInt
// 		for j := i & (i - 1); j > i^j; j = (j - 1) & i {
// 			k := i ^ j
// 			f[i] = min(f[i], f[j]+f[k]+abs(median[j]-median[k]))
// 		}
// 		f[i] += sl
// 	}
// 	return int64(f[u-1])
// }
// 
// //
// 
// // 88. 合并两个有序数组(创建一个新数组)
// func merge(a, b []int) []int {
// 	i, n := 0, len(a)
// 	j, m := 0, len(b)
// 	res := make([]int, 0, n+m)
// 	for {
// 		if i == n {
// 			return append(res, b[j:]...)
// 		}
// 		if j == m {
// 			return append(res, a[i:]...)
// 		}
// 		if a[i] < b[j] {
// 			res = append(res, a[i])
// 			i++
// 		} else {
// 			res = append(res, b[j])
// 			j++
// 		}
// 	}
// }
// 
// func calcSorted(lists [][]int) [][]int {
// 	u := 1 << len(lists)
// 	sorted := make([][]int, u)
// 	for i, a := range lists {
// 		highBit := 1 << i
// 		for s, b := range sorted[:highBit] {
// 			sorted[highBit|s] = merge(a, b)
// 		}
// 	}
// 	return sorted
// }
// 
// // 4. 寻找两个正序数组的中位数
// func findMedianSortedArrays(a, b []int) int {
// 	if len(a) > len(b) {
// 		a, b = b, a
// 	}
// 
// 	m, n := len(a), len(b)
// 	i := sort.Search(m, func(i int) bool {
// 		j := (m+n+1)/2 - i - 2
// 		return a[i] > b[j+1]
// 	}) - 1
// 
// 	j := (m+n+1)/2 - i - 2
// 	if i < 0 {
// 		return b[j]
// 	}
// 	if j < 0 {
// 		return a[i]
// 	}
// 	return max(a[i], b[j])
// }
// 
// func minMergeCost(lists [][]int) int64 {
// 	n := len(lists)
// 	m := n / 2
// 	sorted1 := calcSorted(lists[:m])
// 	sorted2 := calcSorted(lists[m:])
// 
// 	u := 1 << n
// 	half := 1<<m - 1
// 	median := make([]int, u)
// 	for i := 1; i < u; i++ {
// 		// 把 i 分成低 m 位和高 n-m 位
// 		// 低 half 位去 sorted1 中找合并后的数组
// 		// 高 n-half 位去 sorted2 中找合并后的数组
// 		median[i] = findMedianSortedArrays(sorted1[i&half], sorted2[i>>m])
// 	}
// 
// 	f := make([]int, u)
// 	for i := range f {
// 		if i&(i-1) == 0 {
// 			continue
// 		}
// 		f[i] = math.MaxInt
// 		for j := i & (i - 1); j > i^j; j = (j - 1) & i {
// 			k := i ^ j
// 			f[i] = min(f[i], f[j]+f[k]+abs(median[j]-median[k]))
// 		}
// 		f[i] += len(sorted1[i&half]) + len(sorted2[i>>m])
// 	}
// 	return int64(f[u-1])
// }
// 
// func abs(x int) int {
// 	if x < 0 {
// 		return -x
// 	}
// 	return x
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.

TWO POINTERS
O(n) time
O(1) space

Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.

Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Moving both pointers on every comparison

Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.

Usually fails on: A valid pair can be skipped when only one side should move.

Fix: Move exactly one pointer per decision branch based on invariant.

Boundary update without `+1` / `-1`

Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.

Usually fails on: Two-element ranges never converge.

Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.