AlgoMaster Logo

Check if Three Points are Collinear

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

Three points lie on the same line when the direction from the first point to the second matches the direction from the first point to the third. The familiar way to capture direction is slope: the rise over run between point 1 and point 2 should match the rise over run between point 1 and point 3.

Slope uses division, and a vertical line has no run, so the formula divides by zero. A special case for vertical lines patches it, but cross-multiplying the two ratios into a single equality removes the division entirely.

Key Constraints:

  • Coordinates are integers → Integer arithmetic stays exact, so a comparison against zero is reliable with no floating-point rounding to worry about.
  • Vertical lines are possible → Two points can share an x value, which makes the run zero. The method must not divide by the run.
  • Values fit in 32 bits → The differences and their products can exceed 32 bits, so compute the cross product using a 64-bit type to avoid overflow.

Approach 1: Cross Product

Intuition

The two slopes are (y2 - y1) / (x2 - x1) and (y3 - y1) / (x3 - x1). Collinear means they are equal:

(y2 - y1) / (x2 - x1) = (y3 - y1) / (x3 - x1)

Multiplying both sides by the denominators clears the fractions:

(y2 - y1) * (x3 - x1) = (y3 - y1) * (x2 - x1)

This quantity is the cross product of the two direction vectors that start at point 1, the signed area of the parallelogram they span. When the points are collinear, the vectors lie along the same line, the parallelogram is flat, and the area is zero. The test reduces to checking whether the cross product is zero, which works even for vertical lines because nothing is divided.

Algorithm

  1. Compute the direction vector from point 1 to point 2: (x2 - x1, y2 - y1).
  2. Compute the direction vector from point 1 to point 3: (x3 - x1, y3 - y1).
  3. Compute the cross product (y2 - y1) * (x3 - x1) - (y3 - y1) * (x2 - x1).
  4. Return true if the cross product is 0, and false otherwise.

Example Walkthrough

Input:

0
(
1
1
2
,
3
4
1
5
)
point1
0
(
1
2
2
,
3
4
2
5
)
point2
0
(
1
3
2
,
3
4
5
5
)
point3

The three points are (1, 1), (2, 2), and (3, 5). The first direction vector is (2 - 1, 2 - 1) = (1, 1). The second is (3 - 1, 5 - 1) = (2, 4). The cross product is (y2 - y1) * (x3 - x1) - (y3 - y1) * (x2 - x1) = 1 * 2 - 4 * 1 = 2 - 4 = -2. Since the result is not zero, the directions differ, so the points bend at the second point and are not collinear.

false
output

Code