Table of contents
Open Table of contents
Description
Question Link: LeetCode 1291
A positive integer has sequential digits when each digit is exactly one greater than the digit before it. Given the inclusive range from low to high, return every sequential-digit number in that range in ascending order.
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]
For the second example, the four-digit runs from 1234 through 6789 and the five-digit run 12345 are inside the range.
Constraints:
- 10 <= low <= high <= 10^9
Idea
Every answer is a contiguous slice of 123456789. A valid number starts at any digit from 1 through 8 and ends at a later digit, so the longest possible answer is 123456789. There are only 36 multi-digit candidates.
For example, the candidates appear in increasing digit length:
2 digits: 12, 23, 34, ..., 89
3 digits: 123, 234, 345, ..., 789
4 digits: 1234, 2345, ..., 6789
...
9 digits: 123456789
Keep only the candidates between low and high, including both endpoints.
Breadth-first generation
Start a queue with the digits 1 through 9. Each queued number is a valid prefix. When its last digit is less than 9, append the next digit to make its only possible child. Add a number to the answer when it is in range.
The queue visits candidates by digit length and by increasing first digit. Each prefix is generated once. Some implementations sort the collected answer explicitly; the Python queue traversal is already ordered.
Contiguous substring enumeration
Instead, enumerate substring lengths from 2 to 9, then move the starting position from left to right. Convert each candidate to a number and keep it when it is inside the range. This order is already ascending; implementations that scan from each starting position sort the result at the end.
There are at most 45 breadth-first states, including the one-digit seeds, and 36 substring candidates. With the fixed nine-digit bound, both approaches take time and auxiliary space, excluding the returned list. If the digit limit were generalized to D, candidate generation would take time.
Java
package array;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
/** LeetCode 1291: return numbers whose digits increase consecutively. */
public final class SequentialDigits {
private static final String DIGITS = "123456789";
private SequentialDigits() {}
public static List<Integer> sequentialDigits(int low, int high) {
// O(1) time and space for the fixed 9-digit input limit (at most 45 BFS states).
List<Integer> result = new ArrayList<>();
Queue<Integer> queue = new ArrayDeque<>();
for (int digit = 1; digit <= 9; digit++) {
queue.add(digit);
}
while (!queue.isEmpty()) {
int value = queue.remove();
if (value >= low && value <= high) {
result.add(value);
}
int lastDigit = value % 10;
if (lastDigit < 9) {
int next = value * 10 + lastDigit + 1;
if (next <= high) {
queue.add(next);
}
}
}
Collections.sort(result);
return result;
}
public static List<Integer> sequentialDigitsBySubstring(int low, int high) {
// O(1) time and space for the fixed 9-digit input limit (at most 36 substrings).
List<Integer> result = new ArrayList<>();
for (int length = 2; length <= DIGITS.length(); length++) {
for (int start = 0; start + length <= DIGITS.length(); start++) {
int value = Integer.parseInt(DIGITS.substring(start, start + length));
if (value >= low && value <= high) {
result.add(value);
}
}
}
return result;
}
}
Python
from collections import deque
class Solution:
"""Breadth-first generation by appending the next digit."""
def sequentialDigits(self, low: int, high: int) -> list[int]:
result = []
queue = deque(range(1, 10))
# Each of at most 45 sequential-digit prefixes is enqueued once: O(D^2) time.
# The queue holds at most one level of the generation tree: O(D) auxiliary space.
while queue:
number = queue.popleft()
if number > high:
continue
if number >= low:
result.append(number)
last_digit = number % 10
if last_digit < 9:
queue.append(number * 10 + last_digit + 1)
return result
class Solution2:
"""Enumerate contiguous substrings of the fixed digit sequence."""
def sequentialDigits(self, low: int, high: int) -> list[int]:
digits = "123456789"
result = []
# There are at most 36 candidate substrings (O(D^2)); values use O(1) extra space.
for length in range(2, len(digits) + 1):
number = int(digits[:length])
for start in range(10 - length):
if low <= number <= high:
result.append(number)
# Slide one position: remove the leading digit and append the next one.
leading_digit = start + 1
number = (number - leading_digit * 10 ** (length - 1)) * 10
number += leading_digit + length
return result
C++
#ifndef LEETCODE_SEQUENTIALDIGITS_HPP
#define LEETCODE_SEQUENTIALDIGITS_HPP
#include <algorithm>
#include <queue>
#include <string>
#include <vector>
using namespace std;
class SequentialDigitsBFS {
public:
// O(1) time and O(1) auxiliary space for the fixed 9-digit search, excluding output.
vector<int> sequentialDigits(int low, int high) {
queue<int> candidates;
for (int digit = 1; digit <= 9; ++digit) {
candidates.push(digit);
}
vector<int> result;
while (!candidates.empty()) {
const int value = candidates.front();
candidates.pop();
if (value >= low && value <= high) {
result.push_back(value);
}
const int lastDigit = value % 10;
if (lastDigit < 9) {
const int next = value * 10 + lastDigit + 1;
if (next <= high) {
candidates.push(next);
}
}
}
sort(result.begin(), result.end());
return result;
}
};
class SequentialDigitsSubstrings {
public:
// O(1) time and O(1) auxiliary space for the fixed 9-digit search, excluding output.
vector<int> sequentialDigits(int low, int high) {
const string digits = "123456789";
vector<int> result;
for (int length = 2; length <= static_cast<int>(digits.size()); ++length) {
for (int start = 0; start + length <= static_cast<int>(digits.size()); ++start) {
const int value = stoi(digits.substr(start, length));
if (value >= low && value <= high) {
result.push_back(value);
}
}
}
return result;
}
};
#endif // LEETCODE_SEQUENTIALDIGITS_HPP
Rust
use std::collections::VecDeque;
pub struct Solution;
impl Solution {
// O(1) time and space for the fixed nine-digit sequence (at most 45 BFS states).
pub fn sequential_digits(low: i32, high: i32) -> Vec<i32> {
let mut queue: VecDeque<i32> = (1..=9).collect();
let mut result = Vec::new();
while let Some(number) = queue.pop_front() {
if (low..=high).contains(&number) {
result.push(number);
}
let last_digit = number % 10;
if last_digit < 9 {
queue.push_back(number * 10 + last_digit + 1);
}
}
result.sort_unstable();
result
}
// O(1) time and space for the fixed nine-digit sequence (at most 36 substrings).
pub fn sequential_digits_by_substring(low: i32, high: i32) -> Vec<i32> {
let digits = b"123456789";
let mut result = Vec::new();
for start in 0..digits.len() {
let mut number = 0;
for (offset, &digit) in digits[start..].iter().enumerate() {
number = number * 10 + (digit - b'0') as i32;
if offset >= 1 && (low..=high).contains(&number) {
result.push(number);
}
}
}
result.sort_unstable();
result
}
}