Skip to content

Commit 53e5110

Browse files
added check straight line question
1 parent 93c0291 commit 53e5110

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
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.
2+
3+
4+
5+
class Solution {
6+
public:
7+
bool checkStraightLine(vector<vector<int>>& coordinates) {
8+
int x1=coordinates[0][0];
9+
int x2=coordinates[1][0];
10+
11+
int y1=coordinates[0][1];
12+
int y2=coordinates[1][1];
13+
14+
int xDiff=x2-x1;
15+
int yDiff=y2-y1;
16+
17+
// Starting from third point
18+
for (int i = 2; i < coordinates.size(); i++) {
19+
// x3-x1/x2-x1 == y3-y1/y2-y1 should satisfy the condition
20+
// to avoid any zero exception error, we mulitply with difference on either side.
21+
// In the case of a straight line, all points on that line will have the same slope with respect to any two points on the line. So, we can compare the slopes between the initial two points (x1, y1) and (x2, y2) and each subsequent point (currX, currY).
22+
int currX = coordinates[i][0];
23+
int currY = coordinates[i][1];
24+
25+
if ((currX - x1) * yDiff != (currY - y1) * xDiff) {
26+
return false;
27+
}
28+
}
29+
30+
31+
return true;
32+
}
33+
};

0 commit comments

Comments
 (0)