Maximize the Distance Between Points on a Square - Problem

Imagine you're a city planner tasked with placing k emergency stations on the perimeter of a square city block to maximize safety coverage. You want to ensure that the closest distance between any two stations is as large as possible.

Given a square with side length side and corners at (0, 0), (0, side), (side, 0), and (side, side), you have a list of candidate locations points on the boundary where stations can be placed. Each point is represented as [x, y].

Your goal is to select exactly k points from the available locations such that the minimum Manhattan distance between any two selected points is maximized.

The Manhattan distance between two points (x₁, y₁) and (x₂, y₂) is |x₁ - x₂| + |y₁ - y₂|.

Return the maximum possible minimum Manhattan distance between the selected k points.

Input & Output

example_1.py — Small Square
$ Input: side = 2, k = 2, points = [[0,0], [1,0], [2,0], [2,1], [2,2], [1,2], [0,2], [0,1]]
Output: 4
💡 Note: We can select points [0,0] and [2,2] (opposite corners). The Manhattan distance between them is |0-2| + |0-2| = 4, which is the maximum possible minimum distance for k=2 points.
example_2.py — More Points
$ Input: side = 3, k = 3, points = [[0,0], [0,1], [0,2], [0,3], [1,3], [2,3], [3,3], [3,2], [3,1], [3,0], [2,0], [1,0]]
Output: 4
💡 Note: We can select points [0,0], [3,1], and [1,3]. The minimum distance between any pair is 4, achieved by multiple pairs. This gives us optimal spacing for 3 points.
example_3.py — Edge Case
$ Input: side = 1, k = 4, points = [[0,0], [0,1], [1,1], [1,0]]
Output: 2
💡 Note: With only 4 corner points available and needing to select all 4, the minimum distance between adjacent corners is 2 (like [0,0] and [0,1]).

Constraints

  • 1 ≤ side ≤ 109
  • 2 ≤ k ≤ points.length ≤ 105
  • points[i] is on the boundary of the square
  • All points are distinct and lie exactly on the square's perimeter

Visualization

Tap to expand
0side2×side3×side4×sideLinear Coordinate System (Unfolded Perimeter)Binary search finds optimal minimum distance
Understanding the Visualization
1
Map Boundary Points
Convert 2D boundary coordinates to 1D linear positions (bottom→right→top→left)
2
Sort Linear Coordinates
Sort all positions for efficient processing
3
Binary Search
Search for the maximum feasible minimum distance
4
Greedy Validation
For each distance, greedily place k points and verify feasibility
Key Takeaway
🎯 Key Insight: By converting the 2D square boundary to a 1D linear coordinate system, we can efficiently use binary search to find the optimal minimum distance, making this complex optimization problem tractable.
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 18
20.2K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen