Splitting a String Into Descending Consecutive Values

Medium · Backtracking · String · Backtracking

Problem

You are given a string s of digits. Decide whether s can be split into two or more non-empty pieces so that their numeric values, read left to right, are in descending order and each adjacent pair differs by exactly 1.

Pieces may have leading zeros: "0090089" can be split as "0090" and "089", with values 90 and 89. Return true if such a split exists and false otherwise.

Examples

Input: s = "4321"
Output: true

Splitting into 4, 3, 2 and 1 gives consecutive descending values.

Input: s = "532"
Output: false

The splits 5|32, 53|2 and 5|3|2 all have a neighboring pair that does not differ by exactly 1.

Input: s = "0090089"
Output: true

"0090" and "089" have values 90 and 89.

Constraints

Approaches

Follow-up

The search is almost linear because every value after the first is forced. If the gap between pieces could be any positive number, the second piece would also be a free choice, and the search would branch twice before becoming forced.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…