Problem Statement
You are given an array coordinates where each element is a pair [x, y] representing a point on a 2D plane.
Return true if these points all lie on a straight line in the XY-plane, otherwise return false.
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 <= 1000coordinates[i].length == 2-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4- All points are unique.
Approach to Solve the Problem (Simple Language)
Idea:
- Points lie on the same line if the slope between any two points is the same.
- Slope between two points
(x1, y1)and(x2, y2)is:
slope = (y2 - y1) / (x2 - x1)
- To avoid division (and floating-point precision issues), we can compare slopes using cross multiplication:
(y2 - y1)*(x3 - x2) == (y3 - y2)*(x2 - x1)
- This ensures all consecutive points have the same slope.
Steps in short:
- Take the first two points to calculate the initial slope.
- Loop through remaining points:
- For each triplet
(p1, p2, p3), check if cross multiplication condition holds.
- For each triplet
- If any point violates the condition, return
false. - If all points satisfy, return
true.
Java Code Solution
public class CheckStraightLine {
public static boolean checkStraightLine(int[][] coordinates) {
int x0 = coordinates[0][0], y0 = coordinates[0][1];
int x1 = coordinates[1][0], y1 = coordinates[1][1];
for (int i = 2; i < coordinates.length; i++) {
int x = coordinates[i][0], y = coordinates[i][1];
// Check cross multiplication to compare slopes
if ((y1 - y0) * (x - x1) != (y - y1) * (x1 - x0)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[][] coordinates = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}};
boolean result = checkStraightLine(coordinates);
System.out.println("All points lie on a straight line? " + result); // Output: true
}
}
Dry Run Example
Input:
coordinates = [[1,2],[2,3],[3,4],[4,5]]
Step-by-step Execution:
- Take first two points
(1,2)and(2,3):- Initial slope comparison:
(y1 - y0) = 3-2 = 1 (x1 - x0) = 2-1 = 1
- Initial slope comparison:
- Check third point
(3,4):
(y1 - y0)*(x - x1) = 1*(3-2) = 1 (y - y1)*(x1 - x0) = (4-3)*(2-1) = 1 => Equal → OK
- Check fourth point
(4,5):
(y1 - y0)*(x - x1) = 1*(4-2) = 2 (y - y1)*(x1 - x0) = (5-3)*(2-1) = 2 => Equal → OK
- All points satisfy → return
true.
Textual Diagram for Understanding
Points: (1,2),(2,3),(3,4),(4,5) Slope between consecutive points: (1,2)-(2,3) = 1 (2,3)-(3,4) = 1 (3,4)-(4,5) = 1 All slopes equal → points lie on a straight line
Complexity Analysis
- Time Complexity: O(n)
- n = number of points. One pass through all points.
- Space Complexity: O(1)
- Only a few variables used, no extra data structures.
This approach is precise, avoids floating-point division, and works for all integer coordinates.
