#1849

Splitting a String Into Descending Consecutive Values

Medium
StringBacktrackingEnumerationBacktrackingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses backtracking with early stopping to avoid unnecessary checks. By keeping track of the last number used, we can efficiently determine if the next number can be part of a valid split.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a recursive function to explore possible splits of the string.
  2. 2Step 2: For each split, convert the substring to a number and check if it meets the descending order and difference criteria.
  3. 3Step 3: If a valid split is found, return true; otherwise, backtrack.
solution.py11 lines
1def canSplit(s):
2    def backtrack(start, prev):
3        if start == len(s):
4            return prev is not None
5        for end in range(start + 1, len(s) + 1):
6            num = int(s[start:end])
7            if (prev is None or (prev - num == 1 and num < prev)):
8                if backtrack(end, num):
9                    return True
10        return False
11    return backtrack(0, None)

Complexity note: The time complexity is O(n) because we only traverse the string once, and the space complexity is O(n) due to the recursion stack.

  • 1Check for leading zeros when converting substrings to integers.
  • 2Ensure the last number is always smaller than the previous one.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.