Ctrl K

Segments on a Chart

Medium
A weather station logged its readings in readings, where readings[i] = [day, value] means the instrument showed value on day day. A chart is drawn by plotting the points (day on the X axis, value on the Y axis) and joining points that are neighbours by day. Consecutive pieces lying on the same straight line are drawn as one segment. Return the minimum number of segments the chart consists of. The readings are not necessarily sorted by day.
Example 1
readings=[[4, 10], [1, 1], [2, 4], [3, 7], [5, 10]] → 2

Ordered by day, the points (1,1), (2,4), (3,7), (4,10) lie on one segment of slope 3, then (4,10)–(5,10) is flat. That is 2 segments.

Example 2
readings=[[6, 2]] → 0

A single point needs nothing drawn, so the answer is 0.

Example 3
readings=[[1, 5], [2, 3], [3, 5], [4, 3]] → 3

A zigzag: the slope keeps changing, so each of the three pieces is its own segment.

Constraints
  • 1 ≤ len(readings) ≤ 10⁵
  • readings[i] = [day, value]
  • 1 ≤ day, value ≤ 10⁹
  • All days are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSmallest Paddock MediumNearest Points to the Base MediumEqual Window Sums on a Ring MediumEmpty Boxes Between Points MediumEmpty Rectangle From Marked Points Medium
loading Python…
Input
readings=[[4, 10], [1, 1], [2, 4], [3, 7], [5, 10]]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 103 tests on the server, hidden ones included.