07. Max Points on a Line

Difficulty:HardPattern:GCD Slope Hash MapTime:O(n^2)Space:O(n)

Given an array of points where points[i] = [x_i, y_i] represents a point on the 2D plane, return the maximum number of points that lie on the same straight line.

How It Works & Algorithmic Design

Solves using GCD Reduced Normalized Slope Frequency Maps:

  1. Outer Loop: Pick anchor point $i$.
  2. Inner Loop: For each point $j > i$:
    • Compute $\Delta x = x_j - x_i$, $\Delta y = y_j - y_i$.
    • Normalize slope fraction using Greatest Common Divisor: g = gcd(|dx|, |dy|). Divide both by g.
    • Ensure canonical sign (e.g. dx > 0 or if dx === 0, dy = 1).
    • Store slope string key "dy/dx" in frequency map.
  3. Track Maximum: maxPoints = Math.max(maxPoints, slopeMap[key] + 1).

Why This Approach Works Best

Normalizing slopes using GCD avoids floating point precision issues across arbitrary lines in $O(n^2)$ time.

Example Walkthrough

Input Points

[[1,1],[2,2],[3,3]]

Points array.

Slope Alignment

All three points share identical reduced slope 1/1.

Collinear points.

Output

3

Maximum points on a line.

Answer: Max Points on a Line implementation

function maxPoints(points) {
  if (points.length <= 2) return points.length;
  let maxCount = 0;
  function gcd(a, b) {
    return b === 0 ? a : gcd(b, a % b);
  }
  for (let i = 0; i < points.length; i++) {
    const map = new Map();
    let localMax = 0;
    for (let j = i + 1; j < points.length; j++) {
      let dx = points[j][0] - points[i][0];
      let dy = points[j][1] - points[i][1];
      const g = gcd(Math.abs(dx), Math.abs(dy));
      dx /= g; dy /= g;
      if (dx < 0 || (dx === 0 && dy < 0)) { dx = -dx; dy = -dy; }
      const key = `${dy}/${dx}`;
      map.set(key, (map.get(key) || 0) + 1);
      localMax = Math.max(localMax, map.get(key));
    }
    maxCount = Math.max(maxCount, localMax + 1);
  }
  return maxCount;
}

Iterate over anchor points and map collinear frequencies using GCD-reduced slope representations.

Key Takeaways
  • Use GCD tuple reduction to avoid floating point division inaccuracies.

  • Anchor points eliminate duplicate backward line checks.

  • Executes in $O(n^2)$ quadratic time.