Algorithm
Problem Name: 1232. 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.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int xOne = coordinates[1][0];
int yOne = coordinates[1][1];
int dx = xOne - coordinates[0][0];
int dy = yOne - coordinates[0][1];
for (int[] coordinate : coordinates) {
int x = coordinate[0];
int y = coordinate[1];
if (dx * (y - yOne) != dy * (x - xOne)) {
return false;
}
}
return true;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const checkStraightLine = function(coordinates) {
const r = ratio(coordinates[0], coordinates[1])
for(let i = 1, len = coordinates.length; i < len - 1; i++) {
if(ratio(coordinates[i], coordinates[i + 1]) !== r) return false
}
return true
};
function ratio(a, b) {
return (b[1] - a[1]) / (b[0] - a[0])
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def checkStraightLine(self, c: List[List[int]]) -> bool:
return len(set(a[0] == b[0] or (b[1] - a[1]) / (b[0] - a[0]) for a, b in zip(c, c[1:]))) == 1
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _1232_CheckIfItIsAStraightLine
{
public bool CheckStraightLine(int[][] coordinates)
{
int dY = coordinates[1][1] - coordinates[0][1];
int dX = coordinates[1][0] - coordinates[0][0];
for (int i = 2; i < coordinates.Length; i++)
{
if (dX * (coordinates[i][1] - coordinates[0][1]) != dY * (coordinates[i][0] - coordinates[0][0]))
return false;
}
return true;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output