Number of Ways to Separate Numbers - Problem

You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to separate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.

Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: num = "327"
Output: 2
💡 Note: Two valid ways: [3, 27] since 3 ≤ 27, and [327] as single number. Cannot use [32, 7] because 32 > 7.
Example 2 — Single Digit
$ Input: num = "9"
Output: 1
💡 Note: Only one way: [9] as single number.
Example 3 — Leading Zeros
$ Input: num = "094"
Output: 0
💡 Note: No valid splits because numbers cannot have leading zeros. "094", "09", "04", "0" all have leading zeros.

Constraints

  • 1 ≤ num.length ≤ 3500
  • num consists of digits only

Visualization

Tap to expand
Number of Ways to Separate Numbers INPUT String: num = "327" 3 idx 0 2 idx 1 7 idx 2 Constraints: - Non-decreasing order - No leading zeros - All positive integers Possible Splits: "3|27" or "327" "3|2|7" invalid (7>2) "32|7" invalid (7<32) ALGORITHM (DP) 1 Define DP State dp[i][j] = ways ending at i with last number length j 2 Check Valid Split No leading zeros, and prev num <= current num 3 Transition For each position, try all valid prev lengths 4 Sum Results Sum all dp[n][j] mod 10^9 + 7 DP Table Example: len 1 2 3 end 1 1 1 FINAL RESULT Valid Separations Found: Option 1: "327" Single number: 327 Option 2: "3,27" Two numbers: 3, 27 (3 <= 27) OK Output: 2 2 valid ways to separate the string "327" Key Insight: Use Dynamic Programming where dp[i][j] represents the number of valid ways to partition the prefix ending at index i, where the last number has length j. For efficiency, precompute comparisons to check if previous number <= current number in O(1) time using prefix sums or LCP (Longest Common Prefix). TutorialsPoint - Number of Ways to Separate Numbers | Dynamic Programming Approach
Asked in
Google 15 Facebook 12
18.5K Views
Medium Frequency
~35 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen