LeetCode #3710 — HARD

Maximum Partition Factor

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 points, where points[i] = [xi, yi] represents the coordinates of the ith point on the Cartesian plane.

The Manhattan distance between two points points[i] = [xi, yi] and points[j] = [xj, yj] is |xi - xj| + |yi - yj|.

Split the n points into exactly two non-empty groups. The partition factor of a split is the minimum Manhattan distance among all unordered pairs of points that lie in the same group.

Return the maximum possible partition factor over all valid splits.

Note: A group of size 1 contributes no intra-group pairs. When n = 2 (both groups size 1), there are no intra-group pairs, so define the partition factor as 0.

Example 1:

Input: points = [[0,0],[0,2],[2,0],[2,2]]

Output: 4

Explanation:

We split the points into two groups: {[0, 0], [2, 2]} and {[0, 2], [2, 0]}.

  • In the first group, the only pair has Manhattan distance |0 - 2| + |0 - 2| = 4.

  • In the second group, the only pair also has Manhattan distance |0 - 2| + |2 - 0| = 4.

The partition factor of this split is min(4, 4) = 4, which is maximal.

Example 2:

Input: points = [[0,0],[0,1],[10,0]]

Output: 11

Explanation:​​​​​​​

We split the points into two groups: {[0, 1], [10, 0]} and {[0, 0]}.

  • In the first group, the only pair has Manhattan distance |0 - 10| + |1 - 0| = 11.

  • The second group is a singleton, so it contributes no pairs.

The partition factor of this split is 11, which is maximal.

Constraints:

  • 2 <= points.length <= 500
  • points[i] = [xi, yi]
  • -108 <= xi, yi <= 108
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 points, where points[i] = [xi, yi] represents the coordinates of the ith point on the Cartesian plane. The Manhattan distance between two points points[i] = [xi, yi] and points[j] = [xj, yj] is |xi - xj| + |yi - yj|. Split the n points into exactly two non-empty groups. The partition factor of a split is the minimum Manhattan distance among all unordered pairs of points that lie in the same group. Return the maximum possible partition factor over all valid splits. Note: A group of size 1 contributes no intra-group pairs. When n = 2 (both groups size 1), there are no intra-group pairs, so define the partition factor as 0.

Baseline thinking

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

Pattern signal: Array · Binary Search · Union-Find

Example 1

[[0,0],[0,2],[2,0],[2,2]]

Example 2

[[0,0],[0,1],[10,0]]
Step 02

Core Insight

What unlocks the optimal approach

  • Use binary search
  • Binary-search the partition factor <code>D</code> to maximize it
  • For a candidate <code>D</code>, add an edge between points <code>i</code> and <code>j</code> iff <code>Manhattan(i,j) < D</code> (they must be in different groups)
  • Check whether the resulting graph is bipartite
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 #3710: Maximum Partition Factor
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3710: Maximum Partition Factor
// package main
// 
// import (
// 	"slices"
// 	"sort"
// )
// 
// // https://space.bilibili.com/206214
// 
// // 原理见 785. 判断二分图
// func isBipartite(points [][]int, low int) bool {
// 	colors := make([]int8, len(points))
// 
// 	var dfs func(int, int8) bool
// 	dfs = func(x int, c int8) bool {
// 		colors[x] = c
// 		p := points[x]
// 		for y, q := range points {
// 			if y == x || abs(p[0]-q[0])+abs(p[1]-q[1]) >= low { // 符合要求
// 				continue
// 			}
// 			if colors[y] == c || colors[y] == 0 && !dfs(y, -c) {
// 				return false // 不是二分图
// 			}
// 		}
// 		return true
// 	}
// 
// 	// 可能有多个连通块
// 	for i, c := range colors {
// 		if c == 0 && !dfs(i, 1) {
// 			return false
// 		}
// 	}
// 	return true
// }
// 
// func maxPartitionFactor1(points [][]int) int {
// 	n := len(points)
// 	if n == 2 {
// 		return 0
// 	}
// 
// 	// 不想算的话可以写 maxDis = int(2e8)
// 	maxDis := 0
// 	for i, p := range points {
// 		for _, q := range points[:i] {
// 			maxDis = max(maxDis, abs(p[0]-q[0])+abs(p[1]-q[1]))
// 		}
// 	}
// 
// 	return sort.Search(maxDis, func(low int) bool {
// 		// 二分最小的不满足要求的 low+1,就可以得到最大的满足要求的 low
// 		return !isBipartite(points, low+1)
// 	})
// }
// 
// //
// 
// type unionFind struct {
// 	fa  []int
// 	dis []int8 // dis[x] 表示 x 到其代表元的距离
// }
// 
// func newUnionFind(n int) unionFind {
// 	fa := make([]int, n)
// 	dis := make([]int8, n)
// 	for i := range fa {
// 		fa[i] = i
// 	}
// 	return unionFind{fa, dis}
// }
// 
// // 返回 x 所在集合的代表元
// // 同时做路径压缩,也就是把 x 所在集合中的所有元素的 fa 都改成代表元
// func (u unionFind) find(x int) int {
// 	if u.fa[x] != x {
// 		rt := u.find(u.fa[x])
// 		u.dis[x] ^= u.dis[u.fa[x]] // 更新 x 到其代表元的距离
// 		u.fa[x] = rt
// 	}
// 	return u.fa[x]
// }
// 
// // 合并两个互斥的点
// // 如果已经合并,返回是否与已知条件矛盾
// func (u *unionFind) merge(from, to int) bool {
// 	x, y := u.find(from), u.find(to)
// 	if x == y { // from 和 to 在同一个集合,不合并
// 		return u.dis[from] != u.dis[to] // 是否与已知信息矛盾
// 	}
// 	//    2 ------ 4
// 	//   /        /
// 	//  1 ------ 3
// 	// 如果知道 1->2 的距离和 3->4 的距离,现在合并 1 和 3,并传入 1->3 的距离(本题等于 1)
// 	// 由于 1->3->4 和 1->2->4 的距离相等
// 	// 所以 2->4 的距离为 (1->3) + (3->4) - (1->2)
// 	u.dis[x] = 1 ^ u.dis[to] ^ u.dis[from]
// 	u.fa[x] = y
// 	return true
// }
// 
// func maxPartitionFactor(points [][]int) int {
// 	n := len(points)
// 	type tuple struct{ dis, x, y int }
// 	manhattanTuples := make([]tuple, 0, n*(n-1)/2) // 预分配空间
// 	for i, p := range points {
// 		for j, q := range points[:i] {
// 			manhattanTuples = append(manhattanTuples, tuple{abs(p[0]-q[0]) + abs(p[1]-q[1]), i, j})
// 		}
// 	}
// 	slices.SortFunc(manhattanTuples, func(a, b tuple) int { return a.dis - b.dis })
// 
// 	uf := newUnionFind(n)
// 	for _, t := range manhattanTuples {
// 		if !uf.merge(t.x, t.y) {
// 			return t.dis // t.x 和 t.y 必须在同一个集合,t.dis 就是这一划分的最小划分因子
// 		}
// 	}
// 	return 0
// }
// 
// 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(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.

BINARY SEARCH
O(log n) time
O(1) space

Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
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.

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.