#1291
Sequential Digits
MediumEnumerationEnumerationBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach generates sequential digits directly without checking every number. It builds numbers by appending digits in a systematic way, ensuring that only valid sequential numbers are created.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an empty list to store results.
- 2Step 2: Loop through starting digits from 1 to 9.
- 3Step 3: For each starting digit, build sequential numbers by appending the next digit until the number exceeds high.
- 4Step 4: If the generated number is within the range [low, high], add it to the results.
- 5Step 5: Return the sorted results.
solution.py11 lines
1def sequentialDigits(low, high):
2 sequential = []
3 for start in range(1, 10):
4 num = start
5 next_digit = start
6 while num <= high and next_digit < 9:
7 if num >= low:
8 sequential.append(num)
9 next_digit += 1
10 num = num * 10 + next_digit
11 return sorted(sequential)ℹ
Complexity note: The time complexity is O(n) since we only generate valid sequential numbers directly without unnecessary checks. The space complexity is O(n) due to storing the results in a list.
- 1Sequential digits can only be formed by starting from 1 to 9 and appending increasing digits.
- 2The maximum possible sequential digit number is 123456789.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.