#2280

Minimum Lines to Represent a Line Chart

Medium
ArrayMathGeometrySortingNumber TheorySortingGeometry
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages the concept of slopes to determine when three consecutive points are collinear, allowing us to count lines more efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the stockPrices array based on the day.
  2. 2Step 2: Initialize a counter for the number of lines needed.
  3. 3Step 3: Iterate through the sorted points and calculate the slope between the first two points.
  4. 4Step 4: For each subsequent point, check if the slope remains the same; if not, increment the line counter.
  5. 5Step 5: Return the total number of lines counted.
solution.py12 lines
1def minimumLines(stockPrices):
2    stockPrices.sort()
3    if len(stockPrices) < 2:
4        return 0
5    lines = 0
6    for i in range(1, len(stockPrices) - 1):
7        x1, y1 = stockPrices[i - 1]
8        x2, y2 = stockPrices[i]
9        x3, y3 = stockPrices[i + 1]
10        if (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1):
11            lines += 1
12    return lines + 1

Complexity note: The complexity is O(n) because we only iterate through the sorted list once, making it linear in terms of the number of points.

  • 1Understanding the concept of slopes helps in determining collinearity.
  • 2Sorting the points based on the x-axis (days) is crucial for correct slope calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.