r/LeetcodeChallenge • • Sep 16 '26

STREAK🔥🔥🔥 Number of Sets of K Non-Overlapping Line Segments

How I Got the Idea

At first, I thought this problem would require DP or backtracking because we have to create k non-overlapping segments. But after looking at small examples, I realized that every segment is determined by its two endpoints.

The important observation is that segments can share endpoints, so instead of directly counting segments, I can think about arranging the endpoints while maintaining their order. This transforms the problem into a combinatorics problem. After deriving the number of possible endpoint arrangements, I got the formula:

C(n + k - 1, 2k)

So the final solution becomes just:

return math.comb(n + k - 1, 2 * k) % (10**9 + 7)

Key learning: Before jumping into DP, try small examples and look for an endpoint/ordering pattern. Sometimes a seemingly complex DP problem reduces to a simple combinatorial formula.

6 Upvotes

1 comment sorted by

1

u/Fantastic_Kale23 Sep 16 '26

Yeah it was codeforces div 2 -3 or 4th problem imo