HardNo. 0149
Max Points on a Line — LeetCode 149 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Geometry, Array, Hash Table, Math
- On a study list
- Top Interview 150
- 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
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0391 | Perfect Rectangle | Hard |
| 0939 | Minimum Area Rectangle | Medium |
| 0963 | Minimum Area Rectangle II | Medium |
| 2249 | Count Lattice Points Inside a Circle | Medium |
| 0268 | Missing Number | Easy |
| 0380 | Insert Delete GetRandom O(1) | Medium |
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.