Number of Sets of K Non-Overlapping Line Segments - Problem

Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points.

The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.

Return the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, k = 2
Output: 3
💡 Note: With 4 points (0,1,2,3), we can draw 2 non-overlapping segments in 3 ways: [0,1]+[2,3], [0,2]+skip 1 point+[3,3], and [1,3]+skip middle points. Wait, segments must cover 2+ points, so [3,3] is invalid. The valid ways are: segments covering [0,1] and [2,3], segments covering [0,2] and skip, actually this needs more careful analysis.
Example 2 — Minimum Case
$ Input: n = 3, k = 1
Output: 3
💡 Note: With 3 points, we can draw 1 segment in 3 ways: [0,1], [0,2], or [1,2]. Each covers at least 2 points.
Example 3 — Impossible Case
$ Input: n = 3, k = 2
Output: 0
💡 Note: With only 3 points, we cannot draw 2 non-overlapping segments where each covers at least 2 points.

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ k ≤ n/2

Visualization

Tap to expand
K Non-Overlapping Line Segments INPUT 1-D Plane with n=4 points 0 1 2 3 n = 4 (points) k = 2 (segments) Valid Segment Examples: [0,1] [2,3] Constraints: - Non-overlapping - Can share endpoints - Integral coordinates ALGORITHM STEPS 1 Define DP State dp[i][j][started] = ways 2 Base Case dp[i][0][0] = 1 for all i 3 Transition Start/extend/end segment 4 Sum Results Return dp[n-1][k][0] DP Table Structure: i\j 0 1 2 0 1 0 0 1 1 1 0 2 1 3 1 FINAL RESULT All 3 Valid Combinations: 1. [0,1] + [2,3] 2. [0,1] + [1,3] 3. [0,2] + [2,3] Output: 3 OK - Verified Result mod 10^9 + 7 Key Insight: The DP state tracks: position i, segments used j, and whether a segment is currently "started". At each point, we can: (1) skip it, (2) start a new segment, (3) extend current segment, or (4) end current segment. This handles endpoint sharing naturally via the "started" flag. TutorialsPoint - Number of Sets of K Non-Overlapping Line Segments | DP Approach
Asked in
Google 15 Microsoft 12 Amazon 8
23.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