This problem gives you a list of coordinates [day, price] representing a line chart over time. You need to find the minimum number of straight line segments required to represent this chart.
A line segment can cover multiple points only if all those points are collinear—meaning they lie on the exact same line with the same slope. If the price changes direction or the rate of change (slope) varies between two consecutive pairs of points, a new line segment must start.
Google uses this problem to test a candidate's knowledge of Geometry, Sorting, and Precision. Key challenges:
(x1, y1), (x2, y2), (x3, y3) lie on the same line.slope1 == slope2 using division (y/x) is risky due to rounding errors. Using cross-multiplication is the "pro" way to solve this.The pattern is Sorting and Slope Comparison.
day (x-coordinate) to process them chronologically.(y2-y1)/(x2-x1) == (y3-y2)/(x3-x2), use the cross-multiplication formula:
(y2-y1) * (x3-x2) == (y3-y2) * (x2-x1).Points: (1, 1), (2, 2), (3, 3), (4, 5)
Sorted: (1, 1), (2, 2), (3, 3), (4, 5)
(double)dy/dx which leads to precision errors with very large coordinates.Always remember the cross-multiplication trick for geometry problems. A/B = C/D is equivalent to A*D = B*C. This avoids division by zero and floating-point errors, making your code more robust and "interview-ready."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Number of Ways to Place People I | Medium | Solve | |
| Minimum Area Rectangle | Medium | Solve | |
| Make K-Subarray Sums Equal | Medium | Solve | |
| Convex Polygon | Medium | Solve | |
| Find the Count of Numbers Which Are Not Special | Medium | Solve |