HardNo. 0149

Max Points on a Line — LeetCode 149 Python Solution

Topics
Geometry, Array, Hash Table, Math
On a study list
Top Interview 150
Reading time
3 min

The problem

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

Example

Input
points = [[1,1],[2,2],[3,3]]
Output
3

Python solution

PythonSolution
class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        ans = 1
        for i in range(n):
            x1, y1 = points[i]
            for j in range(i + 1, n):
                x2, y2 = points[j]
                cnt = 2
                for k in range(j + 1, n):
                    x3, y3 = points[k]
                    a = (y2 - y1) * (x3 - x1)
                    b = (y3 - y1) * (x2 - x1)
                    cnt += a == b
                ans = max(ans, cnt)
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 149. Max Points on a Line is filed here because LeetCode tags it Math and Geometry, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 149. Max Points on a Line?

LeetCode 149. Max Points on a Line is rated Hard on LeetCode.

What is the time complexity of LeetCode 149. Max Points on a Line?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 149. Max Points on a Line?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 149. Max Points on a Line cover?

LeetCode 149. Max Points on a Line is tagged Geometry, Array, Hash Table and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.