Minimum Lines to Represent a Line Chart - Problem

You are given a 2D integer array stockPrices where stockPrices[i] = [day_i, price_i] indicates the price of the stock on day day_i is price_i.

A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price, and connecting adjacent points.

Return the minimum number of lines needed to represent the line chart.

Input & Output

Example 1 — Basic Case
$ Input: stockPrices = [[1,7],[2,6],[3,5]]
Output: 1
💡 Note: All three points lie on the same line with slope -1. From (1,7) to (2,6): slope = (6-7)/(2-1) = -1. From (2,6) to (3,5): slope = (5-6)/(3-2) = -1. Since slopes are the same, only 1 line is needed.
Example 2 — Slope Change
$ Input: stockPrices = [[1,7],[2,6],[3,5],[5,4]]
Output: 3
💡 Note: Three different slopes: (1,7)→(2,6) has slope -1, (2,6)→(3,5) has slope -1, but (3,5)→(5,4) has slope -0.5. Since the slope changes twice, we need 3 separate line segments.
Example 3 — Two Points
$ Input: stockPrices = [[3,4],[1,2]]
Output: 1
💡 Note: Only two points, so exactly one line segment is needed to connect them.

Constraints

  • 1 ≤ stockPrices.length ≤ 105
  • stockPrices[i].length == 2
  • 1 ≤ dayi, pricei ≤ 109
  • All dayi are distinct

Visualization

Tap to expand
Minimum Lines to Represent a Line Chart INPUT Day (X-axis) Price (Y-axis) (1,7) (2,6) (3,5) stockPrices Array: [1,7] [2,6] [3,5] 3 points on XY plane sorted by day ALGORITHM STEPS (Cross Multiplication) 1 Sort by Day Points already sorted: [1,7],[2,6],[3,5] 2 Calculate Slopes Use cross multiplication to avoid precision loss 3 Compare Adjacent dy1*dx2 == dy2*dx1 ? Slope 1-2: dy1=6-7=-1, dx1=2-1=1 Slope 2-3: dy2=5-6=-1, dx2=3-2=1 (-1)*1 == (-1)*1 --> -1 == -1 Same slope! Collinear points 4 Count Lines If slopes differ, add line Start with 1 if n > 1 FINAL RESULT (1,7) (2,6) (3,5) All 3 points are collinear! One line connects them all Output: 1 OK - Minimum lines = 1 Key Insight: Cross multiplication (dy1*dx2 == dy2*dx1) avoids floating-point precision errors when comparing slopes. If consecutive segments have the same slope, they're collinear and form ONE line. Count lines only when slope changes. Time: O(n log n) for sorting, O(n) for traversal. Space: O(1) extra space (or O(n) if sorting in-place not possible). TutorialsPoint - Minimum Lines to Represent a Line Chart | Cross Multiplication Approach
Asked in
Meta 15 Amazon 12 Google 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen