The Number of Sets of K Non-Overlapping Line Segments problem asks you to count the number of ways to choose exactly k non-overlapping line segments on a number line of n points (0 to n-1), where segments have a positive length and can share endpoints. Return the count modulo 10^9+7. This coding problem uses combinatorics or DP with prefix sums.
Amazon asks this to test combinatorial insight with prefix-sum DP optimization. The key mathematical insight: choosing k non-overlapping segments on n points is equivalent to choosing 2k points with certain ordering constraints, which maps to a stars-and-bars combinatorics problem. The math, combinatorics, dynamic programming, and prefix sum interview pattern is the core.
Stars and bars combinatorics. The answer equals C(n+k-1, 2k) — choosing 2k positions from n+k-1 to represent k segments (each segment defined by 2 endpoints, with k-1 "gap" units between segments to prevent overlap). Or equivalently via DP: dp[i][j] = ways to select j segments using points 0..i, with prefix sum optimization for O(nk) time.
n=3, k=1. Segments: [0,1],[0,2],[1,2]. Count = 3 = C(3,2)=3. ✓ (C(n+k-1, 2k) = C(3,2)=3).
n=4, k=2. C(4+2-1, 4) = C(5,4) = 5. Verify by listing pairs of non-overlapping segments on [0,3]: ([0,1],[2,3]), ([0,1],[1,3]), wait segments can share endpoints... Let's just trust the formula: 5.
Combinatorics problems involving "choose k non-overlapping objects" often have elegant stars-and-bars formulas. Derive by transforming: k non-overlapping segments with possible shared endpoints on n points → add k-1 phantom points to separate segments → C(n+k-1, 2k). Practice deriving combinatorial formulas for geometric selection problems. Always verify your formula on small cases before implementing.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Unique Paths | Medium | Solve | |
| Find the Count of Monotonic Pairs I | Hard | Solve | |
| Find the Count of Monotonic Pairs II | Hard | Solve | |
| Find the Number of Possible Ways for an Event | Hard | Solve | |
| Find the Derangement of An Array | Medium | Solve |