C++ 1232.cpp
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
// straight
int x1 = coordinates[0][0];
int y1 = coordinates[0][1];
bool xonly = true;
bool yonly = true;
for (auto c : coordinates)
{
if (c[0] != x1)
xonly = false;
if (c[1] != y1)
yonly = false;
if (!xonly && !yonly)
break;
}
if (xonly || yonly)
return true;
int dx = coordinates[0][0] - coordinates[1][0];
int dy = coordinates[0][1] - coordinates[1][1];
double epsilon = 1e-15;
double r = double(dx) / dy;
for (int i = 2; i < coordinates.size(); i++)
{
dx = coordinates[i][0] - coordinates[0][0];
dy = coordinates[i][1] - coordinates[0][1];
double r2 = double(dx) / dy;
if (fabs(r2 - r) > 1000*epsilon)
return false;
}
return true;
}
};
Difficulty
and has an acceptance rate of about 40% (700k+ submissions).
Typical patterns to solve this problem:
- Array
- Geometry
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The function determines whether a set of 2-D points, supplied as a vector of integer pairs, all lie on a single straight line. It first checks for the trivial cases of a purely vertical or horizontal line, then computes a reference slope using the first two points and verifies that every subsequent point yields the same slope within a tight tolerance.
Initial Horizontal/Vertical Check
The algorithm extracts the x- and y-coordinates of the first point and uses two Boolean flags, xonly and yonly, to track whether all points share the same x-value (vertical line) or the same y-value (horizontal line). The loop iterates over each coordinate pair, clearing the flags as soon as a differing value is observed. An early break stops the scan once both flags are false, avoiding unnecessary work.
int x1 = coordinates[0][0];
int y1 = coordinates[0][1];
bool xonly = true;
bool yonly = true;
for (auto c : coordinates)
{
if (c[0] != x1)
xonly = false;
if (c[1] != y1)
yonly = false;
if (!xonly && !yonly)
break;
}
if (xonly || yonly)
return true;
If either flag remains true after the scan, the points are confirmed to be collinear on a vertical or horizontal line, and the function returns true immediately.
Slope Calculation
When the points are not all aligned vertically or horizontally, the code computes the differences in x and y between the first two points to obtain a reference slope r. A very small epsilon (1e-15) is defined to tolerate floating-point rounding errors.
int dx = coordinates[0][0] - coordinates[1][0];
int dy = coordinates[0][1] - coordinates[1][1];
double epsilon = 1e-15;
double r = double(dx) / dy;
The division is performed in double precision to preserve accuracy for non-integer slopes.
Iterative Verification
Starting from the third point, the algorithm recomputes the differences relative to the first point, derives a new slope r2, and compares it to the reference slope r. The absolute difference is scaled by a factor of 1000 times epsilon to provide a practical tolerance. If any point deviates beyond this bound, the function returns false. The loop stops as soon as a mismatch is detected, ensuring minimal work.
for (int i = 2; i < coordinates.size(); i++)
{
dx = coordinates[i][0] - coordinates[0][0];
dy = coordinates[i][1] - coordinates[0][1];
double r2 = double(dx) / dy;
if (fabs(r2 - r) > 1000*epsilon)
return false;
}
return true;
Edge Cases Handled
The early vertical/horizontal detection prevents division by zero when the line is perfectly vertical (dy == 0) or horizontal (dx == 0). The same-point scenario, where all coordinates are identical, satisfies both xonly and yonly, causing an immediate true result. The use of a scaled epsilon accommodates the limited precision of floating-point arithmetic, ensuring that points that mathematically lie on the same line but produce minute numerical differences are still accepted.
Performance Optimizations
The code employs several techniques to reduce runtime overhead. The initial scan for uniform x or y values can terminate early once both flags are cleared, avoiding a full traversal of the input when the line is neither vertical nor horizontal. The slope verification loop also exits at the first sign of inconsistency, preventing unnecessary calculations for large datasets. All arithmetic operations are simple integer subtractions followed by a single double division per iteration, keeping the computational cost low. The use of a static epsilon and a constant scaling factor eliminates the need for dynamic tolerance computation.
ELI5 - Simplified Explanation
Imagine you have a bunch of dots scattered on a big piece of paper. This code acts like a little detective to see if all those dots form one perfectly straight line, just like when you use a ruler to draw.
First, the code looks at the very first dot and checks if every other dot is lined up perfectly straight up and down or straight across from side to side. It creates two imaginary paths to see if the dots stay on them.
If the dots are tilting on a slant instead of being perfectly flat or straight up, the code needs to be a bit more clever. It looks at the first two dots to see how steep the slant is. Think of this like checking the angle of a slide at the playground. Once it knows how steep that first bit is, it goes through every single other dot one by one. It measures the distance between the starting dot and each new dot to see if they all follow that same exact slope.
By looking at that slope for every single dot, the code can tell if they are all part of the same straight path. If every dot follows the same angle, the code says the line is straight. If even one dot is a little bit off to the side, it knows the line is wobbly and not perfectly straight.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | |||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality