LeetCode 149 Max Points on Line - Example and Complexity Analysis

Walkthrough and analysis

Trace points = [[0,0], [1,1], [2,2], [1,0]].

Anchor at [0,0]:

  • Slope to [1,1]: dy=1, dx=1 → reduced (1,1)
  • Slope to [2,2]: dy=2, dx=2 → reduced (1,1)
  • Slope to [1,0]: dy=0, dx=1 → reduced (0,1)

Slope map: {(1,1): 2, (0,1): 1}. Max is 22. With anchor, that's 33 collinear points.

Anchor at [1,1]:

  • Slope to [0,0]: (-1,-1) → reduced (1,1)
  • Slope to [2,2]: (1,1) → reduced (1,1)
  • Slope to [1,0]: (-1,0) → reduced (1,0)

Slope map: {(1,1): 2, (1,0): 1}. Same result: 33 collinear.

You check nn anchors. For each, compute slopes to n1n-1 others. That's O(n2)O(n^2) total time.

Each anchor's slope map uses at most O(n)O(n) space.