Ctrl K

Longest Chain of Segments

Medium
You get a list segments, where segments[i] = [start, end] and start < end. A segment [c, d] may follow a segment [a, b] in a chain when b < c, meaning the next one starts strictly after the previous one ends. Return the length of the longest chain. You may take segments in any order and do not have to use all of them.
Example 1
segments=[[1, 4], [5, 6], [2, 3], [4, 8]] → 2

For instance, [2, 3] → [4, 8] or [2, 3] → [5, 6] are chains of length 2. Nothing longer works: [1, 4] and [4, 8] share an endpoint, and [5, 6] does not start after 8.

Example 2
segments=[[-3, -1], [10, 12], [0, 5]] → 3

All three line up: [-3, -1] → [0, 5] → [10, 12].

Example 3
segments=[[0, 9], [1, 8], [2, 7]] → 1
Constraints
  • 1 ≤ len(segments) ≤ 10⁵
  • -1000 ≤ start < end ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Meetings to Cancel MediumA Haul That Splits Three Ways MediumStrongest Product Team MediumBreaking a Chocolate Bar MediumBiggest Number Divisible by Three Hard
loading Python…
Input
segments=[[1, 4], [5, 6], [2, 3], [4, 8]]
Expected
2

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