Number of Ways to Separate Numbers — LeetCode 1977 Python Solution

HardStringDynamic ProgrammingSuffix Array
Problem
#1977
Reading time
5 min

The problem

You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers.

Example

Input
num = "327"
Output
2
Explanation
You could have written down the numbers:

Python solution

Python
class Solution:
    def numberOfCombinations(self, num: str) -> int:
        def cmp(i, j, k):
            x = lcp[i][j]
            return x >= k or num[i + x] >= num[j + x]

        mod = 10**9 + 7
        n = len(num)
        lcp = [[0] * (n + 1) for _ in range(n + 1)]
        for i in range(n - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                if num[i] == num[j]:
                    lcp[i][j] = 1 + lcp[i + 1][j + 1]

        dp = [[0] * (n + 1) for _ in range(n + 1)]
        dp[0][0] = 1
        for i in range(1, n + 1):
            for j in range(1, i + 1):
                v = 0
                if num[i - j] != '0':
                    if i - j - j >= 0 and cmp(i - j, i - j - j, j):
                        v = dp[i - j][j]
                    else:
                        v = dp[i - j][min(j - 1, i - j)]
                dp[i][j] = (dp[i][j - 1] + v) % mod
        return dp[n][n]

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1977. Number of Ways to Separate Numbers 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 1977. Number of Ways to Separate Numbers?
LeetCode 1977. Number of Ways to Separate Numbers is rated Hard on LeetCode.
What is the time complexity of LeetCode 1977. Number of Ways to Separate Numbers?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1977. Number of Ways to Separate Numbers?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1977. Number of Ways to Separate Numbers cover?
LeetCode 1977. Number of Ways to Separate Numbers is tagged String, Dynamic Programming and Suffix Array 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