Check If It Is a Straight Line

You are given an array 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.

Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

 

Constraints:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate point.
 

class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
            double tSlope = 0;
        int length = coordinates.length - 1, i;
        
        double slope = (double)(coordinates[1][1] - coordinates[0][1])/(double)(coordinates[1][0] - coordinates[0][0]);
        
        for(i = 1;i<length;i++){
            tSlope = (double)(coordinates[i+1][1] - coordinates[i][1])/(double)(coordinates[i+1][0] - coordinates[i][0]);
                if(slope != tSlope){
                    return false;
            }
        }
        
        return true;
    }
}


Try it on Leetcode

Here, we are using slope concept in Mathematics.

Consider three points (x1, y1) (x2. y2) (x3,y3)

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

If above condition becomes true then above three points lie on same straight line.

Here, tSlope is temporary slope which will be changed while iterating all coordinates and slope variable is a slope between first two coordinates. Also here, coordinates[i][0] is x coordinate and coordinate [i][1] is y coordinate.

Note:[Please have a look on this to avoid Exception]

Here we are using division so there is a chance for occurrence of Divide By Zero Exception(Run Time Exception). To avoid this, we need to convert all coordinates to double, because any number divided by double or float 0, compiler consider it as a INFINITY and not as RunTimeException. By this way we need to avoid this exception.

In this problem initially we are finding slope for first two coordinates. Then by iterating other coordinates, we are going to take slopes for those also. If any of slope not equals with first slope [i.e., slope between first two coordinates] returns false . Else if all are equal then at end, returns true.

Here, tSlope is temporary slope which will be changed while iterating all coordinates and slope variable is a slope between first two coordinates. Also here, coordinates[i][0] is x coordinate and coordinate [i][1] is y coordinate.

Related Posts:

Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation


Please let us know your views in comment section

Subscribe us to receive updates instantly..

Happy Coding..!!

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II