LeetCode #3464 — HARD

Maximize the Distance Between Points on a Square

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 an integer side, representing the edge length of a square with corners at (0, 0), (0, side), (side, 0), and (side, side) on a Cartesian plane.

You are also given a positive integer k and a 2D integer array points, where points[i] = [xi, yi] represents the coordinate of a point lying on the boundary of the square.

You need to select k elements among points such that the minimum Manhattan distance between any two points is maximized.

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

The Manhattan Distance between two cells (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.

Example 1:

Input: side = 2, points = [[0,2],[2,0],[2,2],[0,0]], k = 4

Output: 2

Explanation:

Select all four points.

Example 2:

Input: side = 2, points = [[0,0],[1,2],[2,0],[2,2],[2,1]], k = 4

Output: 1

Explanation:

Select the points (0, 0), (2, 0), (2, 2), and (2, 1).

Example 3:

Input: side = 2, points = [[0,0],[0,1],[0,2],[1,2],[2,0],[2,2],[2,1]], k = 5

Output: 1

Explanation:

Select the points (0, 0), (0, 1), (0, 2), (1, 2), and (2, 2).

Constraints:

  • 1 <= side <= 109
  • 4 <= points.length <= min(4 * side, 15 * 103)
  • points[i] == [xi, yi]
  • The input is generated such that:
    • points[i] lies on the boundary of the square.
    • All points[i] are unique.
  • 4 <= k <= min(25, points.length)
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 an integer side, representing the edge length of a square with corners at (0, 0), (0, side), (side, 0), and (side, side) on a Cartesian plane. You are also given a positive integer k and a 2D integer array points, where points[i] = [xi, yi] represents the coordinate of a point lying on the boundary of the square. You need to select k elements among points such that the minimum Manhattan distance between any two points is maximized. Return the maximum possible minimum Manhattan distance between the selected k points. The Manhattan Distance between two cells (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.

Baseline thinking

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

Pattern signal: Array · Math · Binary Search

Example 1

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

Example 2

2
[[0,0],[1,2],[2,0],[2,2],[2,1]]
4

Example 3

2
[[0,0],[0,1],[0,2],[1,2],[2,0],[2,2],[2,1]]
5

Related Problems

  • Maximum Number of Integers to Choose From a Range II (maximum-number-of-integers-to-choose-from-a-range-ii)
  • Maximum Points Inside the Square (maximum-points-inside-the-square)
Step 02

Core Insight

What unlocks the optimal approach

  • Can we use binary search for this problem?
  • Think of the coordinates on a straight line in clockwise order.
  • Binary search on the minimum Manhattan distance <code>x</code>.
  • During the binary search, for each coordinate, find the immediate next coordinate with distance >= <code>x</code>.
  • Greedily select up to <code>k</code> coordinates.
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 #3464: Maximize the Distance Between Points on a Square
class Solution {
  public int maxDistance(int side, int[][] points, int k) {
    List<int[]> ordered = getOrderedPoints(side, points);
    int l = 0;
    int r = side;

    while (l < r) {
      final int m = (l + r + 1) / 2;
      if (isValidDistance(ordered, k, m))
        l = m;
      else
        r = m - 1;
    }

    return l;
  }

  private record Sequence(int startX, int startY, int endX, int endY, int length) {}

  // Returns true if we can select `k` points such that the minimum Manhattan
  // distance between any two consecutive chosen points is at least `m`.
  private boolean isValidDistance(List<int[]> ordered, int k, int d) {
    Deque<Sequence> dq = new ArrayDeque<>(List.of(new Sequence(
        ordered.get(0)[0], ordered.get(0)[1], ordered.get(0)[0], ordered.get(0)[1], 1)));
    int maxLength = 1;

    for (int i = 1; i < ordered.size(); ++i) {
      final int x = ordered.get(i)[0];
      final int y = ordered.get(i)[1];
      int startX = x;
      int startY = y;
      int length = 1;
      while (!dq.isEmpty() &&
             (Math.abs(x - dq.peekFirst().endX()) + Math.abs(y - dq.peekFirst().endY()) >= d)) {
        if (Math.abs(x - dq.peekFirst().startX()) + Math.abs(y - dq.peekFirst().startY()) >= d &&
            dq.peekFirst().length() + 1 >= length) {
          startX = dq.peekFirst().startX();
          startY = dq.peekFirst().startY();
          length = dq.peekFirst().length() + 1;
          maxLength = Math.max(maxLength, length);
        }
        dq.pollFirst();
      }
      dq.addLast(new Sequence(startX, startY, x, y, length));
    }

    return maxLength >= k;
  }

  // Returns the ordered points on the perimeter of a square of side length
  // `side`, starting from left, top, right, and bottom boundaries.
  private List<int[]> getOrderedPoints(int side, int[][] points) {
    List<int[]> left = new ArrayList<>();
    List<int[]> top = new ArrayList<>();
    List<int[]> right = new ArrayList<>();
    List<int[]> bottom = new ArrayList<>();

    for (int[] point : points) {
      final int x = point[0];
      final int y = point[1];
      if (x == 0 && y > 0)
        left.add(point);
      else if (x > 0 && y == side)
        top.add(point);
      else if (x == side && y < side)
        right.add(point);
      else
        bottom.add(point);
    }

    left.sort(Comparator.comparingInt(a -> a[1]));
    top.sort(Comparator.comparingInt(a -> a[0]));
    right.sort(Comparator.comparingInt(a -> - a[1]));
    bottom.sort(Comparator.comparingInt(a -> - a[0]));
    List<int[]> ordered = new ArrayList<>();
    ordered.addAll(left);
    ordered.addAll(top);
    ordered.addAll(right);
    ordered.addAll(bottom);
    return ordered;
  }
}
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.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

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.