VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-maximum-points-on-same-line/

⇱ Count maximum points on same line - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count maximum points on same line

Last Updated : 7 Jul, 2025

Given n point on a 2D plane as pair of (x, y) co-ordinates, we need to find maximum number of point which lie on the same line.

Examples: 

Input : points[] = {-1, 1}, {0, 0}, {1, 1},
{2, 2}, {3, 3}, {3, 4}
Output : 4
Then maximum number of point which lie on same
line are 4, those point are {0, 0}, {1, 1}, {2, 2},
{3, 3}

For each point p, calculate its slope with other points and use a map to record how many points have same slope, by which we can find out how many points are on same line with p as their one point. For each point keep doing the same thing and update the maximum number of point count found so far.

Some things to note in implementation are: 

  1. if two point are (x1, y1) and (x2, y2) then their slope will be (y2 – y1) / (x2 – x1) which can be a double value and can cause precision problems. To get rid of the precision problems, we treat slope as pair ((y2 - y1), (x2 – x1)) instead of ratio and reduce pair by their gcd before inserting into map. In below code points which are vertical or repeated are treated separately.
  2. If we use Hash Map or Dictionary for storing the slope pair, then total time complexity of solution will be O(n^2) and space complexity will be O(n).

Output
4

Time Complexity:O(n2logn), where n denoting length of string.
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: