Taro Logo

Sequential Digits

#1 Most AskedMedium
2 views
Topics:
Arrays

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


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the possible value ranges for `low` and `high`, and are we guaranteed that `low` is always less than or equal to `high`?
  2. Can `low` or `high` be negative, or will they always be positive integers?
  3. What should be returned if no integers with sequential digits fall within the given `low` and `high` range (e.g., should we return an empty list)?
  4. Does the range inclusive of `high` and `low` mean we should include `low` and `high` in our results if they themselves have sequential digits?
  5. Is there any specific maximum bound for `high` that we need to worry about regarding integer overflow?

Brute Force Solution

Approach

To solve this problem using a brute force approach, we want to look at every single number we can possibly form where the digits go up in order. We then check each of those numbers to see if it falls within the range we were given, and keep the ones that fit.

Here's how the algorithm would work step-by-step:

  1. Start by generating all possible numbers where each digit is exactly one greater than the digit that came before it, such as starting with one followed by two, then two followed by three, and so on.
  2. Make sure to include numbers of all different lengths, starting from two-digit numbers all the way up to much longer numbers where the digits increase sequentially.
  3. Take each of these generated numbers one by one and compare it against the lower and upper bounds of your target range.
  4. Check if the number is greater than or equal to the starting limit and less than or equal to the ending limit.
  5. If the number successfully falls inside this range, save it to your collection of valid answers.
  6. Repeat this check for every single sequentially-digited number you generated until you have tested all possible combinations.
  7. Finally, arrange all the saved valid numbers in numerical order from smallest to largest and present them as your final result.

Code Implementation

def sequentialDigits(low: int, high: int) -> list[int]:
    # Generate all possible sequential digit numbers across all valid lengths to check against range
    all_sequential = []
    sample_string = "123456789"
    
    for length in range(1, 10):
        for start_index in range(10 - length):
            substring = sample_string[start_index:start_index + length]
            all_sequential.append(int(substring))

    # Filter the generated numbers to keep only those that fall strictly within the target limits
    valid_numbers = []
    for current_number in all_sequential:
        if low <= current_number <= high:
            valid_numbers.append(current_number)

    # Sort the filtered collection in ascending order to satisfy the final ordering requirements
    valid_numbers.sort()
    return valid_numbers

Big(O) Analysis

Time Complexity
O(1) – The number of possible integers with sequential digits is strictly finite because digits must increase sequentially from 1 to 9, meaning there are only 36 possible numbers we can ever generate regardless of the input range. Generating these numbers, checking them against the lower and upper bounds, and sorting them therefore takes a constant number of operations. Consequently, the total time complexity is O(1) as the cost does not scale with the size of the input range.
Space Complexity
O(1) – The auxiliary space complexity is considered constant because the maximum number of sequentially-digited numbers that can possibly be generated is strictly bounded to a total of 36 combinations, regardless of the input range. The result list stores at most these 36 integers, and the generation logic only requires a few primitive variables for tracking loops and bounds. Since the memory used does not scale with the size of the inputs or expand dynamically beyond this small fixed set of combinations, the auxiliary space remains O(1).

Optimal Solution

Approach

Instead of checking every single number to see if it fits the rules, the optimal strategy generates only the numbers that have sequentially rising digits. By building these special numbers systematically from scratch, we can quickly find all the ones that fall within our target range.

Here's how the algorithm would work step-by-step:

  1. Recognize that any number with sequential digits is built using a simple pattern: starting from a specific digit and counting upwards until the end.
  2. Generate all possible starting digits from one through eight.
  3. For each starting digit, continuously append the next higher digit to build a sequence, stopping before the number exceeds the maximum allowed limit.
  4. Keep track of every number successfully built using this pattern.
  5. Check which of these built numbers fall between your lower and upper limits.
  6. Sort the qualifying numbers from smallest to largest and present them as the final result.

Code Implementation

class Solution:
    def sequential_digits(self, low_limit: int, high_limit: int) -> list[int]:
        valid_sequential_numbers = []

        # Generate all numbers with sequential digits systematically rather than checking every integer.
        for start_digit in range(1, 10):
            current_number = start_digit
            for next_digit in range(start_digit + 1, 10):
                current_number = current_number * 10 + next_digit
                if current_number > high_limit:
                    break
                if current_number >= low_limit:
                    valid_sequential_numbers.append(current_number)

        # Sorting ensures the generated numbers are returned in strictly ascending order as required.
        return sorted(valid_sequential_numbers)

Big(O) Analysis

Time Complexity
O(1) – The time complexity is constant because the number of sequential digits that can possibly be generated is strictly bounded between 12 and 123456789. Regardless of the low and high input limits, the algorithm only loops through 9 possible starting digits and builds at most 36 total numbers. This means the number of operations does not scale with the size of the input, resulting in an optimal O(1) runtime.
Space Complexity
O(1) – The space complexity is considered O(1) auxiliary space because the total number of integers with sequential digits is strictly bounded and finite. Regardless of the input range boundaries, there are at most 36 possible sequential numbers that can ever be generated. The list storing these intermediate numbers and the final sorted result requires a constant maximum amount of extra memory that does not scale with the size of the input limits.

Edge Cases

Low and high are equal and form a valid sequential digit number
How to Handle:
The algorithm will generate this number and include it in the result list if it falls within the range.
No sequential digits exist within the given low and high range
How to Handle:
The result list remains empty and is returned correctly without any errors.
Inputs at the extreme constraints like low equals 10 and high equals 10 to the power of 9
How to Handle:
Using 32-bit or 64-bit integers prevents overflow since the maximum valid sequential number is 123456789 which fits easily in standard integer types.
Range is very narrow and excludes all possible sequential numbers
How to Handle:
The filtering step naturally omits any generated numbers that fall outside the boundaries.
Low is greater than high
How to Handle:
The generator loop will not execute and an empty list will be returned immediately.
Single digit numbers like low equals 1 and high equals 9
How to Handle:
Single digits do not have a previous digit to compare against so sequential digit generation typically starts at length two unless explicitly handled.
Generated sequential number exceeds the high limit
How to Handle:
A break condition stops the generation process as soon as numbers exceed the upper limit since they are produced in strictly increasing order.
0/2 completed