This is an interview question: "Find all collinear points in a given set".
As I understand, they ask to print out the points, which lie in the same line (and every two points are always collinear). I would suggest the following.
Line
(pair of doubles) and Point
(pair of integers).HashMap<Line, List<Point>)
Line
connecting the points and add the line with those points to the multimap.Finally, the multimap contains the lines as the keys and a list collinear points for each line as its value.
The complexity is O(N^2). Does it make sense ? Are there better solutions ?
One common way of checking if three points are collinear is by finding the area of the triangle formed by the points. The area will be zero if the points are collinear.
Slope formula method to find that points are collinear. Three or more points are collinear, if slope of any two pairs of points is same. With three points A, B and C, three pairs of points can be formed, they are: AB, BC and AC. If Slope of AB = slope of BC = slope of AC, then A, B and C are collinear points.
Three or more points are said to be collinear if they all lie on the same straight line. If A, B and C are collinear then m A B = m B C ( = m A C ) .
Collinear points are the points that lie on the same straight line or in a single line. If two or more than two points lie on a line close to or far from each other, then they are said to be collinear, in Euclidean geometry.
One of interesting solution for this problem is here.
Time complexity is O(n2)
Space Complexity- O(n)
https://stackoverflow.com/a/50207802/7438973
Take a look at the two methods described in http://www.cs.princeton.edu/courses/archive/spring03/cs226/assignments/lines.html .
To find 4 or more collinear points given N points, the brute-force method has a time complexity of O(N^4), but a better method does it in O(N^2 log N).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With