Algorithm/NeetCode

Sequential Digits

Tony Lim 2024. 11. 25. 13:44
728x90

https://leetcode.com/problems/sequential-digits/

class Solution:
    def sequentialDigits(self, low:int , high: int):
        res = []
        low_digit , high_digit = len(str(low)), len(str(high))

        for digits in range(low_digit, high_digit + 1):
            for start in range(1,9):
                if start + digits > 10:
                    break
                num = start
                prev = start
                for i in range(digits - 1):
                    num = num * 10
                    prev += 1
                    num += prev
                if low <= num <= high:
                    res.append(num)
        return res

first check if start + digits is less or equal to 10

e.g) if start =6 ,digit =4 it means we can have 6 7 8 9  but if stat = 7 , 7 8 9 10  which is impossible.

 

class Solution:
    def sequentialDigits(self, low:int , high: int):
        res = []
        queue = deque(range(1,10))

        while queue:
            n = queue.popleft()
            if n > high:
                continue

            if low <= n <= high:
                res.append(n)

            ones = n % 10
            if ones < 9:
                queue.append(n * 10 + (ones + 1))
        return res

queue will eventually be empty because when 2345 is poped from queue and become 23456 and append to the queue.

later on when 23456 is poped it will be greater than high so will be skipped

we used queue because we want sorted at the last.

if it were stack order would go like 1234 12345 and so on 

 

 

 

 

728x90