Splitting a String Into Descending Consecutive Values — LeetCode 1849 Python Solution

MediumStringBacktrackingEnumeration
Problem
#1849
Reading time
3 min

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

Example

Input
s = "1234"
Output
false
Explanation
There is no valid way to split s.

Python solution

Python
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)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n), where n is the length of the string auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1849. Splitting a String Into Descending Consecutive Values is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1849. Splitting a String Into Descending Consecutive Values?
LeetCode 1849. Splitting a String Into Descending Consecutive Values is rated Medium on LeetCode.
What is the time complexity of LeetCode 1849. Splitting a String Into Descending Consecutive Values?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1849. Splitting a String Into Descending Consecutive Values?
The Python solution on this page uses O(n), where n is the length of the string auxiliary space.
What topics does LeetCode 1849. Splitting a String Into Descending Consecutive Values cover?
LeetCode 1849. Splitting a String Into Descending Consecutive Values is tagged String, Backtracking and Enumeration 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