Leetcode #1621: Number of Sets of K Non-Overlapping Line Segments
In this guide, we solve Leetcode #1621 Number of Sets of K Non-Overlapping Line Segments in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, Dynamic Programming, Combinatorics
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 4, k = 2
Output: 5
Explanation: The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
Python Solution
class Solution:
def numberOfSets(self, n: int, k: int) -> int:
mod = 10**9 + 7
f = [[0] * (k + 1) for _ in range(n + 1)]
g = [[0] * (k + 1) for _ in range(n + 1)]
f[1][0] = 1
for i in range(2, n + 1):
for j in range(k + 1):
f[i][j] = (f[i - 1][j] + g[i - 1][j]) % mod
g[i][j] = g[i - 1][j]
if j:
g[i][j] += f[i - 1][j - 1]
g[i][j] %= mod
g[i][j] += g[i - 1][j - 1]
g[i][j] %= mod
return (f[-1][-1] + g[-1][-1]) % mod
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.