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:

- Slope of the first line:
- Slope of the second line:

We can cross-multiply to avoid division:

$(y2 - y1) \times (x3 - x2) \neq (y3 - y2) \times (x2 - x1)$

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:

$\text{Area} = \frac{1}{2} \times \left| x1 \times (y2 - y3) + x2 \times (y3 - y1) + x3 \times (y1 - y2) \right|$

If the area is zero, the points are on a straight line.

Here’s the full code: