Max Points on a Line — LeetCode 149 Python Solution
- Problem
- #149
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
On a study list
This problem is on Top Interview 150.
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.