Maximum Partition Factor Problem
Description
LeetCode Problem 3710.
You are given a 2D integer array points, where points[i] = [x_i, y_i] represents the coordinates of the i^th point on the Cartesian plane.
The Manhattan distance between two points points[i] = [x_i, y_i] and points[j] = [x_j, y_j] is |x_i - x_j| + |y_i - y_j|.
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 <= 500points[i] = [x_i, y_i]-10^8 <= x_i, y_i <= 10^8
Solution
Approach: Binary Search + Bipartite Check
Ask whether a partition factor of at least d is possible. That holds exactly when every pair of points closer than d ends up in different groups. Build a graph whose edges join points at Manhattan distance below d; the split exists if and only if this graph is bipartite, which a DFS two-colouring decides.
Feasibility only gets harder as d grows, so binary search the largest feasible d. With n = 2 there are no same-group pairs and the answer is 0. With n >= 3, two points must share a group, so the answer is finite (at most 4 * 10^8).
Complexity: O(n^2 log D) time, where D = 4 * 10^8 bounds the distance, and O(n^2) space for the distance table.
class Solution:
def maxPartitionFactor(self, points: List[List[int]]) -> int:
n = len(points)
if n == 2:
return 0
dist = [[abs(p[0] - q[0]) + abs(p[1] - q[1]) for q in points] for p in points]
def ok(d: int) -> bool:
# edges join points closer than d; they must be 2-colourable
color = [-1] * n
for s in range(n):
if color[s] != -1:
continue
color[s] = 0
stack = [s]
while stack:
u = stack.pop()
for v in range(n):
if v != u and dist[u][v] < d:
if color[v] == -1:
color[v] = color[u] ^ 1
stack.append(v)
elif color[v] == color[u]:
return False
return True
lo, hi = 0, 4 * 10**8 + 1
while lo < hi:
mid = (lo + hi + 1) >> 1
if ok(mid):
lo = mid
else:
hi = mid - 1
return lo