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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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) = 2median(a) = 3 and median(b) = 2cost = len(a) + len(b) + abs(median(a) - median(b)) = 3 + 2 + abs(3 - 2) = 6So 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) = 3median(a) = 3 and median(b) = 7cost = len(a) + len(b) + abs(median(a) - median(b)) = 5 + 3 + abs(3 - 7) = 12So 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) = 4median(a) = 1 and median(b) = 4cost = len(a) + len(b) + abs(median(a) - median(b)) = 3 + 4 + abs(1 - 4) = 10So 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) = 1median(a) = 1 and median(b) = 3cost = len(a) + len(b) + abs(median(a) - median(b)) = 1 + 1 + abs(1 - 3) = 4So 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 <= 121 <= lists[i].length <= 500-109 <= lists[i][j] <= 109lists[i] is sorted in non-decreasing order.lists[i].length will not exceed 2000.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.
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
[[1,3,5],[2,4],[6,7,8]]
[[1,1,5],[1,4,7,8]]
[[1],[3]]
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
// }
// 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
}
# Accepted solution for LeetCode #3801: Minimum Cost to Merge Sorted Lists
# Time: O(l * nlogn + 2^n * log(n * l) * n * logl + 3^n), n = len(lists), l = max(len(list) for list in lists)
# Space: O(n * l + 2^n)
import heapq
import bisect
# dp, sort, heap, binary search, submask enumeration
class Solution(object):
def minMergeCost(self, lists):
"""
:type lists: List[List[int]]
:rtype: int
"""
INF = float("inf")
def merge(lists):
result = []
min_heap = [(lists[i][0], i, 0) for i in xrange(len(lists))]
heapq.heapify(min_heap)
while min_heap:
x, i, j = heapq.heappop(min_heap)
result.append(x)
if j+1 < len(lists[i]):
heapq.heappush(min_heap, (lists[i][j+1], i, j+1))
return result
def binary_search(left, right, check):
while left <= right:
mid = left+(right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
def check(x):
return sum(bisect.bisect_right(lists[i], sorted_vals[x]) for i in range(len(lists)) if mask&(1<<i)) >= (dp1[mask]+1)//2
dp1 = [0]*(1<<len(lists))
for i in xrange(len(lists)): # Time: O(2^n)
dp1[1<<i] = len(lists[i])
for mask in xrange(1, len(dp1)): # Time: O(2^n)
dp1[mask] = dp1[mask^(mask&-mask)]+dp1[mask&-mask]
sorted_vals = merge(lists) # Time: O(l * nlogn)
sorted_vals = [sorted_vals[i] for i in xrange(len(sorted_vals)) if i+1 == len(sorted_vals) or sorted_vals[i+1] != sorted_vals[i]]
dp2 = [0]*(1<<len(lists))
for mask in xrange(1, len(dp2)): # Time: O(2^n * log(n * l) * n * logl)
dp2[mask] = sorted_vals[binary_search(0, len(sorted_vals)-1, check)]
dp3 = [0]*(1<<len(lists))
for mask in xrange(1, len(dp3)): # Time: O(3^n)
if mask&(mask-1) == 0:
continue
dp3[mask] = INF
submask = (mask-1)&mask
while submask > mask^submask:
dp3[mask] = min(dp3[mask], dp3[submask]+dp3[mask^submask]+abs(dp2[submask]-dp2[mask^submask])+dp1[mask])
submask = (submask-1)&mask
return dp3[-1]
// Accepted solution for LeetCode #3801: Minimum Cost to Merge Sorted Lists
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// 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
// }
// Accepted solution for LeetCode #3801: Minimum Cost to Merge Sorted Lists
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// 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
// }
Use this to step through a reusable interview workflow for this problem.
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.
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.
Review these before coding to avoid predictable interview regressions.
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.
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.
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.
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.