You are given a list of points on a flat grid. Each point is a pair [x, y] of whole numbers, and no two points are the same.
Find the straight line that passes through as many of the points as possible, and return how many points it passes through.
Example 1
Input: points = [[0,0],[1,2],[2,4],[1,0]] Output: 3 Why: (0,0), (1,2) and (2,4) all lie on y = 2x
2 more examples and the constraints
Example 2
Input: points = [[2,3]] Output: 1 Why: a single point is on a line by itself
Example 3
Input: points = [[0,1],[2,2],[4,3],[0,3],[1,2],[6,4]] Output: 4 Why: (0,1), (2,2), (4,3), (6,4) climb 1 for every 2 across
Constraints
- 1 ≤ number of points ≤ 300
- −10,000 ≤ x, y ≤ 10,000
- All points are different
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every pair, count the lineO(n³)
- Slope map per anchorO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 300 points | Verdict |
|---|---|---|---|
| Every pair, count the line | O(n³) | Mention it, then move on | |
| Slope map per anchor | O(n²) | Best; one map per anchor |
n = how many points there are.
Edge cases to test
- One or two points. The answer is the number of points; there is no pair to compare for a single point.
- Vertical lines. dx is 0. A float slope would divide by zero; the key 1/0 handles it.
- Opposite directions. (1, −1) and (−1, 1) are the same line through the anchor. Fixing the sign makes them one key.
- Close but different slopes. 10000/9999 and 10001/10000 must stay apart, which floats may not do.
Common mistakes
- Using floating-point slopes, which can merge two different lines or split one.
- Reducing by the gcd but not fixing the sign, so one line becomes two keys.
- Returning the largest count without adding 1 for the anchor itself.
How to talk through it
- 1Clarify. Are the points all different? How many can there be? Are coordinates whole numbers?
- 2Give the brute force. Every pair fixes a line; counting points on it is O(n³).
- 3Fix an anchor. Lines through one point differ only by slope, so a map from slope to count does one anchor in O(n).
- 4Make the slope exact. Reduce (dx, dy) by their gcd and fix the sign; say why floats are unsafe.
- 5Test out loud. Run one point, a vertical line and a line with points on both sides of the anchor.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?