Python 0149.py
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
if len(points) < 2:
return len(points)
all = defaultdict(set)
for p1 in range(len(points)):
for p2 in range(p1 + 1, len(points)):
x1 = points[p1][0]
y1 = points[p1][1]
x2 = points[p2][0]
y2 = points[p2][1]
dx = x1 - x2
dy = y1 - y2
# a = (y1-y2) / (x1-x2)
# y = ax + b => b = y - ax
a = float("inf")
b = x1
if dx != 0:
a = dy / dx
b = y1 - a * x1
all[tuple([a, b])].add(p1)
all[tuple([a, b])].add(p2)
result = 0
for a in all:
result = max(result, len(all[a]))
return result
Difficulty
and has an acceptance rate of about 31% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Geometry
- Hash Table
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation defines a Solution class with a maxPoints method that receives a list of 2-D points and returns the size of the largest set of points that lie on a single straight line. The algorithm first handles trivial inputs, then enumerates every unordered pair of points, computes a canonical representation of the line passing through the pair, and aggregates point indices that share the same line. Finally, it extracts the maximum cardinality among all line groups.
Key Steps
Early return for small inputs
if len(points) < 2:
return len(points)
When the input contains zero or one point, the answer is trivially the number of points, so the method returns immediately without further work.
Data structure for line groups
all = defaultdict(set)
A defaultdict of sets is created. Each key will be a tuple (a, b) that uniquely identifies a line, and the associated set stores the indices of points that belong to that line. Using a set automatically eliminates duplicate indices that may arise from processing multiple pairs on the same line.
Pairwise enumeration
for p1 in range(len(points)):
for p2 in range(p1 + 1, len(points)):
x1 = points[p1][0]
y1 = points[p1][1]
x2 = points[p2][0]
y2 = points[p2][1]
Two nested loops iterate over all unordered pairs of points. The outer loop selects the first point index p1; the inner loop selects a second index p2 that is strictly greater than p1, guaranteeing each pair is examined exactly once.
Computing a canonical line representation
dx = x1 - x2
dy = y1 - y2
a = float("inf")
b = x1
if dx != 0:
a = dy / dx
b = y1 - a * x1
The differences dx and dy are used to compute the slope a and intercept b. For non-vertical lines (dx != 0), the slope is dy / dx and the intercept follows from y = a*x + b. For vertical lines (dx == 0), the slope is set to positive infinity and the intercept is chosen as the constant x coordinate (b = x1). This convention yields a unique key for each geometric line, including vertical ones.
Updating the line-to-points map
all[tuple([a, b])].add(p1)
all[tuple([a, b])].add(p2)
The tuple (a, b) is used as a dictionary key. The current pair’s point indices are added to the corresponding set. Because the container is a set, repeated insertion of the same index (which can happen when multiple pairs belong to the same line) has no effect.
Determining the maximum collinear count
result = 0
for a in all:
result = max(result, len(all[a]))
return result
The method iterates over all stored line keys, computes the size of each associated point set, and keeps the largest size encountered. The final result is returned as the answer.
Edge Cases Handled
The algorithm explicitly treats inputs with fewer than two points as a base case, returning the correct count without entering the main logic.
Vertical lines are identified by a zero denominator (dx == 0). By assigning an infinite slope and using the constant x coordinate as the intercept, vertical lines receive a distinct and consistent key, ensuring they are grouped correctly with other points that share the same vertical line.
Duplicate points are naturally handled by the set structure: if the same point appears in multiple pairs that map to the same line, its index is stored only once in the set, preventing artificial inflation of the count.
Performance Optimizations
The use of a defaultdict eliminates the need for explicit existence checks before inserting into the map, reducing overhead in the inner loop.
Storing point indices in a set rather than a list prevents duplicate entries without additional logic, which keeps the aggregation step lightweight.
Choosing a tuple of floating-point values (a, b) as the dictionary key provides O(1) average-case access for insertion and lookup, allowing the algorithm to maintain a single pass over the pairwise combinations.
The early return for trivial inputs avoids unnecessary allocation of the defaultdict and the double loop when the answer is already known.
ELI5 - Simplified Explanation
Imagine you have a big sheet of paper and you stick lots of tiny star stickers all over it. Each star is at a special spot that you can find by counting how far across and how far up it is. This code helps figure out how many stars can be connected by drawing a perfectly straight line.
First, the code checks if there are at least two stars to connect. If there is only one star, it knows a line needs more than that.
Next, it looks at every single pair of stars on the paper. It draws an invisible line between each pair to see how slanted the line is and where it sits. It uses two secret numbers for every line to describe it, almost like an address for the path. When it finds a path that goes through a few stars, it remembers which ones are on that path by putting them into a group.
After it checks all the pairs and puts the stars into their correct groups based on the lines, it counts how many stars ended up in each group. It keeps track of the biggest group it found, because that represents the most stars that can all sit on one straight line together.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | C# | Go | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| Dijkstra-Edu | Java | |||||||||
| everthis | JS | |||||||||
| FelixFan1122 | C# | |||||||||
| fsq | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| Dijkstra-Edu | Java | |||||||||
| everthis | JavaScript | |||||||||
| FelixFan1122 | C# | |||||||||
| fsq | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ |
Videos
Similar Problems
- problem 356: Line Reflection
- problem 2280: Minimum Lines to Represent a Line Chart
Solved On The Same Day
- problem 205: Isomorphic Strings
- problem 905: Sort Array By Parity
- problem 922: Sort Array By Parity II
- problem 2423: Remove Letter To Equalize Frequency
- problem 18: 4Sum
- problem 80: Remove Duplicates from Sorted Array II
- problem 92: Reverse Linked List II
- problem 93: Restore IP Addresses
- problem 384: Shuffle an Array
- problem 1143: Longest Common Subsequence
- problem 1615: Maximal Network Rank
- problem 32: Longest Valid Parentheses
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality