Skip to content

1232. Check If It Is a Straight Line 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  bool checkStraightLine(vector<vector<int>>& coordinates) {
    int x0 = coordinates[0][0];
    int y0 = coordinates[0][1];
    int x1 = coordinates[1][0];
    int y1 = coordinates[1][1];
    int dx = x1 - x0;
    int dy = y1 - y0;

    for (int i = 2; i < coordinates.size(); ++i) {
      int x = coordinates[i][0];
      int y = coordinates[i][1];
      if ((x - x0) * dy != (y - y0) * dx)
        return false;
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public boolean checkStraightLine(int[][] coordinates) {
    int x0 = coordinates[0][0];
    int y0 = coordinates[0][1];
    int x1 = coordinates[1][0];
    int y1 = coordinates[1][1];
    int dx = x1 - x0;
    int dy = y1 - y0;

    for (int i = 2; i < coordinates.length; ++i) {
      int x = coordinates[i][0];
      int y = coordinates[i][1];
      if ((x - x0) * dy != (y - y0) * dx)
        return false;
    }

    return true;
  }
}
1
2
3
4
5
6
7
class Solution:
  def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
    x0, y0, x1, y1 = *coordinates[0], *coordinates[1]
    dx = x1 - x0
    dy = y1 - y0

    return all((x - x0) * dy == (y - y0) * dx for x, y in coordinates)