Back to questions
Given an array of three points, return if the points are on a straight line, and if they are not.
Input: points = [[2, 1], [3, 4], [5, 6]]
Output: False
Input: points = [[0, 0], [1, 1], [2, 2]]
Output: True
One way to solve this problem is by comparing the slopes of lines formed by the three points. If the slopes of any two lines are the same, it means the three points lie on a straight line.
Given two points and , the slope of the line connecting them can be calculated with the formula . However, when , this results in a division by zero, which can cause an error. While we could handle this with an if-condition, there’s a simpler approach.
Let’s say the three points are , , and . We want to check if these points are on a straight line. Instead of directly comparing the slopes:
We can cross-multiply to avoid division:
This avoids the division by zero problem, and that’s the method we’ll use in the implementation.
Here’s the code:
Another way to solve this problem is by calculating the area formed by the three points as a triangle. If the points lie on a straight line, the area will be zero. We can use the shoelace formula to calculate the area.
According to the shoelace formula, the area of a triangle with points , , and is:
If the area is zero, the points are on a straight line.
Here’s the full code: