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

Problem: https://leetcode.com/problems/check-if-it-is-a-straight-line/?envType=study-plan&id=programming-skills-i

Example 1:

[Solved] <a href="https://leetcode.com/problems/check-if-it-is-a-straight-line/?envType=study-plan&id=programming-skills-i" target="_blank" rel="noreferrer noopener">Check If It Is a Straight Line</a>
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

[Solved] <a href="https://leetcode.com/problems/check-if-it-is-a-straight-line/?envType=study-plan&id=programming-skills-i" target="_blank" rel="noreferrer noopener">Check If It Is a Straight Line</a>
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.

Solution

Intuition

The slope of a line is (y2 – y1) / (x2 – x1). If the slope of the line is the same for all points, then the points are on the same line.

Runtime
0 ms
Beats
100%
Accepted Solutions Runtime Distribution (%)

Memory
41.8 MB
Beats
94.86%

Approach

We can use the slope of the first two points to check if the rest of the points are on the same line. If the slope is the same for all points, then the points are on the same line.

Complexity
  • Time complexity: O(N)
  • Space complexity: O(1)
class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        int x1 = coordinates[0][0];
        int y1 = coordinates[0][1];
        int x2 = coordinates[1][0];
        int y2 = coordinates[1][1];
        for(int i = 2; i < coordinates.length; i++){
            int x = coordinates[i][0];
            int y = coordinates[i][1];
            if((y2 - y1) * (x - x1) != (y - y1) * (x2 - x1)){
                return false;
            }
        }
        return true;   
    }
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *