LeetCode 1232: Check If It Is a Straight Line Solution

Master LeetCode problem 1232 (Check If It Is a Straight Line), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1232. Check If It Is a Straight Line

Problem Explanation

Explanation:

To check if the given set of coordinates lie on a straight line, we can use the slope formula for a line passing through two points. If all points lie on the same line, the slopes between consecutive points should be equal.

  1. Calculate the slope between the first two points.
  2. Iterate through the remaining points and calculate the slope between each point and the first point.
  3. If all slopes are equal, the points lie on a straight line.

Time complexity: O(n) Space complexity: O(1)

:

Solution Code

class Solution {
    public boolean checkStraightLine(int[][] coordinates) {
        if (coordinates.length == 2) {
            return true;
        }
        
        int x0 = coordinates[0][0];
        int y0 = coordinates[0][1];
        int x1 = coordinates[1][0];
        int y1 = coordinates[1][1];
        
        for (int i = 2; i < coordinates.length; i++) {
            int xi = coordinates[i][0];
            int yi = coordinates[i][1];
            if ((yi - y0) * (x1 - x0) != (y1 - y0) * (xi - x0)) {
                return false;
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1232 (Check If It Is a Straight Line)?

This page provides optimized solutions for LeetCode problem 1232 (Check If It Is a Straight Line) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1232 (Check If It Is a Straight Line)?

The time complexity for LeetCode 1232 (Check If It Is a Straight Line) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1232 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1232 in Java, C++, or Python.

Back to LeetCode Solutions