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 <= 500points[i] = [xi, yi]-108 <= xi, yi <= 108When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The problem asks us to divide a set of points into two groups such that the minimum distance between points within the same group is maximized. If two points have a distance strictly less than a threshold D, they cannot belong to the same group, meaning there must be an edge between them in an inconsistency graph that requires 2-coloring. Therefore, finding the maximum partition factor corresponds to finding the largest threshold D such that the graph of edges with weight strictly less than D is bipartite.
Here's how the algorithm would work step-by-step:
def max_partition_factor(points: list[list[int]]) -> int:
num_points = len(points)
if num_points <= 2:
return 0
# Generate all pairwise Manhattan distances between the given points.
edge_list = []
for first_idx in range(num_points):
first_x, first_y = points[first_idx]
for second_idx in range(first_idx + 1, num_points):
second_x, second_y = points[second_idx]
distance = abs(first_x - second_x) + abs(first_y - second_y)
edge_list.append((distance, first_idx, second_idx))
# Sort all edges in ascending order to test possible thresholds.
edge_list.sort()
def is_bipartite_with_threshold(limit: int) -> bool:
adjacency = [[] for _ in range(num_points)]
for distance, first_node, second_node in edge_list:
if distance >= limit:
break
adjacency[first_node].append(second_node)
adjacency[second_node].append(first_node)
color = [-1] * num_points
for start_node in range(num_points):
if color[start_node] == -1:
color[start_node] = 0
queue = [start_node]
queue_head = 0
while queue_head < len(queue):
curr_node = queue[queue_head]
queue_head += 1
for neighbor in adjacency[curr_node]:
if color[neighbor] == -1:
color[neighbor] = 1 - color[curr_node]
queue.append(neighbor)
elif color[neighbor] == color[curr_node]:
return False
return True
# Binary search over the sorted edge weights to find the maximum valid threshold.
low_index = 0
high_index = len(edge_list) - 1
best_answer = 0
while low_index <= high_index:
mid_index = (low_index + high_index) // 2
current_distance = edge_list[mid_index][0]
if is_bipartite_with_threshold(current_distance):
best_answer = current_distance
low_index = mid_index + 1
else:
high_index = mid_index - 1
# Check if all edges can be satisfied without violating bipartiteness.
if is_bipartite_with_threshold(edge_list[-1][0] + 1):
return edge_list[-1][0]
return best_answer
The problem asks for the maximum partition factor when splitting points into two sets, where the partition factor is the minimum distance between points placed in the same set. If we want all pairs within the same set to have distance at least a threshold, any pair with distance strictly less than the threshold must be placed in different sets. This condition is equivalent to the graph of pairs with distance less than the threshold being bipartite, which allows binary searching the maximum valid threshold.
Here's how the algorithm would work step-by-step:
def max_partition_factor(points):
total_points = len(points)
if total_points == 2:
return 0
# Precompute pairwise Manhattan distances and collect all unique distances
distances = []
for first_idx in range(total_points):
first_x, first_y = points[first_idx]
for second_idx in range(first_idx + 1, total_points):
second_x, second_y = points[second_idx]
dist = abs(first_x - second_x) + abs(first_y - second_y)
distances.append(dist)
unique_distances = sorted(list(set(distances)))
# Check if a 2-coloring exists such that all pairs with distance < d have different colors
def is_bipartite(threshold):
adjacency = [[] for _ in range(total_points)]
for first_idx in range(total_points):
first_x, first_y = points[first_idx]
for second_idx in range(first_idx + 1, total_points):
second_x, second_y = points[second_idx]
if abs(first_x - second_x) + abs(first_y - second_y) < threshold:
adjacency[first_idx].append(second_idx)
adjacency[second_idx].append(first_idx)
color = [-1] * total_points
for start_node in range(total_points):
if color[start_node] == -1:
color[start_node] = 0
queue = [start_node]
queue_head = 0
while queue_head < len(queue):
curr_node = queue[queue_head]
queue_head += 1
for neighbor in adjacency[curr_node]:
if color[neighbor] == -1:
color[neighbor] = 1 - color[curr_node]
queue.append(neighbor)
elif color[neighbor] == color[curr_node]:
return False
return True
# Binary search over possible distance values
low_idx = 0
high_idx = len(unique_distances) - 1
best_factor = unique_distances[0]
while low_idx <= high_idx:
mid_idx = (low_idx + high_idx) // 2
candidate_dist = unique_distances[mid_idx]
if is_bipartite(candidate_dist):
best_factor = candidate_dist
low_idx = mid_idx + 1
else:
high_idx = mid_idx - 1
return best_factor
| Case | How to Handle |
|---|---|
| Empty or null input array | Return zero or an appropriate sentinel value immediately after checking for null or empty status at the start of the function. |
| Array with a single element | Treat the entire array as a single partition and return the factor value for that single element without attempting further splits. |
| Maximum possible input size with millions of elements | Use an efficient linear or log-linear dynamic programming or greedy approach to prevent time limit exceeded errors. |
| Array with all identical values | Ensure the partitioning logic correctly evaluates all possible segment lengths and handles uniform distributions without infinite loops. |
| Array containing negative numbers and zeros | Ensure segment factor calculations correctly account for sign changes and products or sums involving negative values. |
| Extreme boundary values exceeding standard integer limits | Use 64-bit integer types like long in Java or standard large integer handling to prevent arithmetic overflow during calculations. |
| Inputs with highly skewed distributions requiring specific partition lengths | Validate that constraint checks or window bounds prevent invalid segmentations where no legal partition exists. |
| Multiple valid partitions yielding the exact same maximum factor | Return the maximum partition factor value itself since any optimal arrangement achieves the target metric. |