Sequential Digits Problem
Description
LeetCode Problem 1291.
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]
Constraints:
10 <= low <= high <= 10^9
Solution
Approach: Enumerate Substrings of "123456789"
A number with sequential digits is a run of consecutive digits, so it is a substring of "123456789" of length 2 to 9 (low >= 10, so one digit is never enough). There are only 8 + 7 + ... + 1 = 36 such numbers, so we can generate them all and keep those in [low, high].
Generating them by length first and by starting digit second gives them in increasing order: a shorter number is always smaller than a longer one, and among numbers of the same length a later start gives a larger number. So the result needs no sort.
Complexity: O(1) time and space: at most 36 candidates of at most 9 digits.
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
digits = "123456789"
result = []
# Shorter numbers are smaller, and for one length a later start is larger,
# so this order is already sorted.
for length in range(2, 10):
for start in range(10 - length):
x = int(digits[start:start + length])
if low <= x <= high:
result.append(x)
return result