Splitting a String Into Descending Consecutive Values Problem
Description
LeetCode Problem 1849.
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.
- For example, 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 by1, so this way is valid. - Another example, the string
s = "001"can be split into["0", "01"],["00", "1"], or["0", "0", "1"]. However all the 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.
Example 1:
Input: s = "1234"
Output: false
Explanation: There is no valid way to split s.
Example 2:
Input: s = "050043"
Output: true
Explanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3].
The values are in descending order with adjacent values differing by 1.
Example 3:
Input: s = "9080701"
Output: false
Explanation: There is no valid way to split s.
Constraints:
1 <= s.length <= 20sonly consists of digits.
Solution
Approach: DFS
Try every way to cut the string into pieces from the left, using dfs(i, x): i is where the next piece starts and x is the previous piece's value (-1 before the first piece).
Extend a piece one digit at a time to get its value y. The piece is allowed if it is the first one, or if x - y == 1; then recurse from the next position. Reaching the end of the string means a valid split. The first piece must leave at least one digit for the rest, so it stops one character early.
Complexity: The first piece has O(n) choices and after that each piece is forced, so about O(n2) time and O(n) space.
class Solution:
def splitString(self, s: str) -> bool:
def dfs(i: int, x: int) -> bool:
if i >= len(s):
return True
y = 0
r = len(s) - 1 if x < 0 else len(s)
for j in range(i, r):
y = y * 10 + int(s[j])
if (x < 0 or x - y == 1) and dfs(j + 1, y):
return True
return False
return dfs(0, -1)