Check If Points Lie on a Straight Line

How to check if points lie on a straight line.

Given an array of coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

Coordinates contains no duplicate point.

For Example –

Example 1:

Input: { [1,2], [2,3], [3,4], [4,5], [5,6], [6,7]}

Output: true

In this example, coordinate lies on a straight line.

Example 2:

Input: [[1,1], [2,2], [3,4], [4,5], [5,6], [7,7]]

Output: false

The coordinates does not lie on a straight line.

Let’s discuss how we can solve this problem.

Programming Tutorials

Programming Questions on Arrays

Programming Questions on Linked List

Programming Questions on String

Check If Points Lie on a Straight Line – Java Code

We can solve this problem by using this Mathematical Property.

If the slopes of lines formed between each point and the first point are equal, then all those points are collinear i.e. in a straight line.

That means, if slope(line between point 1 and point 2) = slope(line between point 1 and point 3) = … = …, then points 1, 2, 3, … are collinear or in a straight line.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.