Number of Sets of K Non-Overlapping Line Segments — LeetCode 1621 Python Solution

MediumMathDynamic ProgrammingCombinatorics
Problem
#1621
Reading time
3 min

The 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.

Example

Input
n = 4, k = 2
Output
5
Explanation
The two line segments are shown in red and blue.

Python solution

Python
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

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments?
LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments is rated Medium on LeetCode.
What topics does LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments cover?
LeetCode 1621. Number of Sets of K Non-Overlapping Line Segments is tagged Math, Dynamic Programming and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview