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

Imagine you're a city planner working on a 1-dimensional street with n evenly spaced points numbered from 0 to n-1. Your task is to determine how many different ways you can draw exactly k non-overlapping line segments to represent different zones or districts.

Key Requirements:

  • Each line segment must connect at least 2 points
  • Line segments are non-overlapping (they can share endpoints but not interior points)
  • You need exactly k segments
  • Not all points need to be covered
  • Return the count modulo 109 + 7

Example: With points [0, 1, 2, 3] and k=2, you could draw segments [0,1] and [2,3], or [0,2] and [3,3], etc.

Input & Output

example_1.py โ€” Basic case
$ Input: n = 4, k = 2
โ€บ Output: 5
๐Ÿ’ก Note: With 4 points [0,1,2,3] and k=2 segments, we can place: [0,1]+[2,3], [0,2]+[3,3], [0,0]+[1,2], [0,0]+[2,3], [1,1]+[2,3]. Total: 5 ways.
example_2.py โ€” Edge case
$ Input: n = 3, k = 1
โ€บ Output: 3
๐Ÿ’ก Note: With 3 points and 1 segment, we can place segment at: [0,1], [0,2], or [1,2]. Total: 3 ways.
example_3.py โ€” Zero segments
$ Input: n = 5, k = 0
โ€บ Output: 1
๐Ÿ’ก Note: There's exactly 1 way to draw 0 segments: draw nothing.

Constraints

  • 2 โ‰ค n โ‰ค 1000
  • 1 โ‰ค k โ‰ค 1000
  • Line segments must cover at least 2 points
  • Segments are non-overlapping but can share endpoints

Visualization

Tap to expand
๐ŸŒ‰ Bridge Building ProblemRiver01234Bridge 1Bridge 2Mathematical Solution:Problem: Place k non-overlapping segments on n pointsKey insight: This is equivalent to stars and barsFormula: C(n + k - 1, 2k)โ€ข Each segment needs 2 endpointsโ€ข k segments need 2k endpoints totalโ€ข Choose from expanded space of n+k-1 positionsExample: n=5, k=2 โ†’ C(6,4) = 15 ways
Understanding the Visualization
1
Setup
We have n positions (0 to n-1) where we can place bridge supports
2
Constraint
Each bridge must span at least 2 positions and bridges cannot overlap
3
Insight
This becomes a combinatorial problem: choosing 2k endpoints from n+k-1 positions
4
Formula
Apply C(n+k-1, 2k) using modular arithmetic
Key Takeaway
๐ŸŽฏ Key Insight: The problem transforms into a beautiful combinatorial formula C(n+k-1, 2k) by recognizing the relationship between segment placement and choosing endpoints in an expanded space.
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
28.5K Views
Medium Frequency
~25 min Avg. Time
842 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