Similar Problems

Similar Problems not available

Sequential Digits - Leetcode Solution

Companies:

LeetCode:  Sequential Digits Leetcode Solution

Difficulty: Unknown

Topics: unknown  

Problem Statement: 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: Input: low = 100, high = 300 Output: [123,234]

Solution: The approach for this problem can be to check all numbers between the range (low, high) and check if they have sequential digits. If a number has sequential digits, add it to the result list.

To check if a number has sequential digits, we can extract all its digits and check if the difference between any two adjacent digits is equal to 1. If all the differences are 1, then the number has sequential digits.

We need to consider all possible length of sequential digits from 2 to 9. For each length, we can generate all possible numbers of that length which have sequential digits and add them to the result list if they lie in the given range.

Code:

class Solution:
    def sequentialDigits(self, low: int, high: int) -> List[int]:
        digits = "123456789" # All possible digits
        
        res = []
        for length in range(2, 10): # Check for all possible length of sequential digits
            for i in range(0, 10 - length): # Generate all possible starting positions
                num = int(digits[i:i+length]) # Extract the number from digits
                if low <= num <= high: 
                    res.append(num) # Add to the result list if it lies in range
        return res

Time Complexity: As we are checking all possible numbers in the given range, the time complexity of the above solution will be O(N), where N is the number of integers between low and high.

Space Complexity: The space complexity of the above solution will be O(N), where N is the number of integers between low and high that have sequential digits.

Sequential Digits Solution Code

1