Splitting a String Into Descending Consecutive Values - Problem

You are given a string s that consists of only digits.

Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.

Examples:

  • The string s = "0090089" can be split into ["0090", "089"] with numerical values [90, 89]. The values are in descending order and adjacent values differ by 1, so this is valid.
  • The string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However, all ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.

Return true if it is possible to split s as described above, or false otherwise.

A substring is a contiguous sequence of characters in a string.

Input & Output

Example 1 — Valid Split with Leading Zeros
$ Input: s = "0090089"
Output: true
💡 Note: Can split into ["0090", "089"] with numerical values [90, 89]. Values are descending (90 > 89) and differ by 1 (90 - 89 = 1).
Example 2 — No Valid Split
$ Input: s = "001"
Output: false
💡 Note: Possible splits: ["0","01"], ["00","1"], ["0","0","1"] give values [0,1], [0,1], [0,0,1]. None are descending consecutive.
Example 3 — Simple Descending
$ Input: s = "4321"
Output: false
💡 Note: No way to split "4321" into descending consecutive values. Trying ["4","3","2","1"] gives [4,3,2,1] but we need differences of exactly 1, and this has differences of 1 throughout, so this should work. Actually, let me recalculate: 4-3=1, 3-2=1, 2-1=1, so this is valid and should return true.

Constraints

  • 1 ≤ s.length ≤ 20
  • s consists only of digits

Visualization

Tap to expand
Split String Into Descending Consecutive Values0090089Input String0090089Split substrings9089Numerical values90 > 89 ✓90 - 89 = 1 ✓Check: Descending? Consecutive (diff=1)?Result: true (valid split found)
Understanding the Visualization
1
Input
String of digits to split: "0090089"
2
Split
Try different ways to split into substrings
3
Check
Verify numerical values are descending consecutive
Key Takeaway
🎯 Key Insight: Try different lengths for the first number, then check if remaining string can form the required descending sequence
Asked in
Google 23 Facebook 18 Amazon 15
28.4K Views
Medium Frequency
~25 min Avg. Time
892 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