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
The problem asks to find all integers within a given range [low, high] that have sequential digits (each digit is one more than the previous digit). The solution uses a straightforward enumeration approach.
The core idea is to generate all possible sequential digit numbers and then filter those that fall within the specified range.
Generate Sequential Numbers: We iterate through possible starting digits (1 to 8). For each starting digit, we build sequential numbers by appending the next digit until we reach 9. This efficiently generates all possible sequential digit numbers.
Filtering: We check if each generated number is within the [low, high]
range. If it is, we add it to the result list.
Sorting: Finally, we sort the result list to satisfy the requirement of a sorted output.
Time Complexity: The time complexity is dominated by the nested loops that generate sequential numbers. The outer loop runs 8 times (starting digits 1 to 8), and the inner loop runs a maximum of 9 times (appending digits until 9). Thus, the generation step takes O(1) time, as it's bounded by a constant (a maximum of 72 iterations). Sorting the result list adds O(N log N) time, where N is the number of sequential numbers within the range. In the worst case, N could be large, but it's still polynomial. Overall, the time complexity is effectively O(N log N), dominated by sorting. If we consider the constant upper bound for generation, it can also be viewed as just O(N log N).
Space Complexity: The space complexity is determined by the size of the ans
list (the list of sequential numbers found within the range). In the worst-case scenario, the list could contain a large number of elements (though still polynomial in the size of the input range). So, the space complexity is O(N), where N is the number of sequential numbers within the range.
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
ans = []
for i in range(1, 9): # Iterate through possible starting digits
x = i
for j in range(i + 1, 10): # Build sequential number
x = x * 10 + j
if low <= x <= high: # Check if within range
ans.append(x)
return sorted(ans) # Sort the result
The other languages (Java, C++, Go, TypeScript) follow the same algorithmic approach; only the syntax differs. They all have the same time and space complexity.