648. Descending Steps Split

Medium3.5 points estimatedStringBacktracking3 hints

A countdown display receives a string s of digits with the separators removed. Cutting s into two or more consecutive pieces and reading each piece as a whole number (leading zeros are allowed and simply ignored) gives a list of numbers. The display is valid if this list goes down by exactly one at every step, for example 9, 8, 7.

Return true if some way of cutting s makes the display valid, and false otherwise. The pieces must cover the whole string in order, and there must be at least two of them.

Example 1

Input:
s = "4321"
Output:
true
Explanation:

Cut into 4 | 3 | 2 | 1, a countdown by one.

Example 2

Input:
s = "0701700699"
Output:
true
Explanation:

The pieces 0701, 700, 699 read as 701, 700 and 699, so the display is valid.

Example 3

Input:
s = "1357"
Output:
false
Explanation:

No cut works: for example, 1 is not followed by 0 and 13 is not followed by 12.

Constraints

  • 2 ≤ s.length ≤ 15
  • s consists only of digits.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n^2)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…