Sequential Digits (LeetCode 1291): Solution and Explanation
A number has sequential digits when each digit is one more than the one before, like 123 or 4567. Given low and high, return every such number in [low, high] in sorted order.
Intuition
The range can be a billion numbers wide, so testing each one is out. Turn the problem around: how many sequential-digit numbers exist at all?
Pick the first digit and the length, and the rest of the number is forced. That means every sequential-digit number is a contiguous slice of the string "123456789". With two or more digits there are only 8 + 7 + ... + 1 = 36 of them.
If you generate them by length, shortest first, and within a length slide the window from left to right, the numbers come out in increasing order. You only need lengths between the digit counts of low and high, and a simple range check keeps the ones that fit.
Approach: Sliding window over "123456789"
- Let
digits = "123456789"and start an empty result list. - For each length from the number of digits in
lowto the number of digits inhigh: - Slide a window of that length across
digitsand convert each slice to an integer. - Append the number if
low <= num <= high. - Return the list, which is already sorted.
Step-by-step example
low = 100, high = 300
- Both low and high have 3 digits, so only windows of length 3 matter.
- Window at 0 gives 123: 100 <= 123 <= 300, keep it.
- Window at 1 gives 234, also in range, keep it.
- Window at 2 gives 345 > 300, skip. 456, 567, 678 and 789 are also too big.
- Return [123, 234].
Code: Python, Java, C++
1class Solution:
2 def sequentialDigits(self, low: int, high: int) -> List[int]:
3 digits = "123456789"
4 result = []
5 for length in range(len(str(low)), len(str(high)) + 1):
6 for start in range(10 - length):
7 num = int(digits[start:start + length])
8 if low <= num <= high:
9 result.append(num)
10 return result1class Solution {
2 public List<Integer> sequentialDigits(int low, int high) {
3 String digits = "123456789";
4 List<Integer> result = new ArrayList<>();
5 int lo = String.valueOf(low).length(), hi = String.valueOf(high).length();
6 for (int len = lo; len <= hi; len++) {
7 for (int start = 0; start + len <= 9; start++) {
8 int num = Integer.parseInt(digits.substring(start, start + len));
9 if (num >= low && num <= high) result.add(num);
10 }
11 }
12 return result;
13 }
14}1class Solution {
2public:
3 vector<int> sequentialDigits(int low, int high) {
4 string digits = "123456789";
5 vector<int> result;
6 int lo = to_string(low).size(), hi = to_string(high).size();
7 for (int len = lo; len <= hi; len++) {
8 for (int start = 0; start + len <= 9; start++) {
9 int num = stoi(digits.substr(start, len));
10 if (num >= low && num <= high) result.push_back(num);
11 }
12 }
13 return result;
14 }
15};Time and space complexity
O(1)
At most 36 slices are generated, each with at most 9 digits, no matter how wide the range is.
O(1)
Apart from the output (at most 36 numbers), only loop counters are stored.
Other approaches
BFS from single digits (time O(1), space O(1))
Start a queue with 1..9 and repeatedly append the next digit (n * 10 + last + 1) while the last digit is below 9. The queue visits numbers in increasing order, and you keep those in range. Same O(1) bound.
Scan the whole range (time O((high - low) log high), space O(1))
Check every integer from low to high for sequential digits. Correct but up to a billion checks, far too slow.
Common mistakes
- Scanning the range instead of generating candidates, which times out.
- Generating by starting digit first (12, 123, 1234, ..., 23, 234, ...), which produces an unsorted list unless you sort it afterwards.
- Letting the window run past the end of "123456789"; a length-L window can only start at positions 0 to 9 - L.
- Assuming high has at most 9 digits. high can be 10^9, which has 10 digits; that length simply has no windows.
Frequently asked questions
Why is the output sorted without sorting?
Every number with fewer digits is smaller than every number with more digits, and for a fixed length the window further right starts with a larger digit. Generating length by length, left to right, therefore yields increasing order.
How many sequential-digit numbers are there?
For length L there are 10 - L of them, so lengths 2 to 9 give 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36.
Could I just hard-code the 36 numbers?
Yes, a precomputed sorted list filtered by the range is also O(1). The sliding window shows where the list comes from and is easy to explain in an interview.