1
+ '''
2
+
3
+ Description:
4
+
5
+ An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
6
+
7
+ Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
8
+
9
+
10
+
11
+ Example 1:
12
+
13
+ Input: low = 100, high = 300
14
+ Output: [123,234]
15
+
16
+
17
+
18
+ Example 2:
19
+
20
+ Input: low = 1000, high = 13000
21
+ Output: [1234,2345,3456,4567,5678,6789,12345]
22
+
23
+
24
+ Constraints:
25
+
26
+ 10 <= low <= high <= 10^9
27
+
28
+ '''
29
+
30
+
31
+ from typing import List
32
+ class Solution :
33
+ def sequentialDigits (self , low : int , high : int ) -> List [int ]:
34
+
35
+
36
+ output = []
37
+
38
+ digit_stack = list ( range (1 ,10 ) )
39
+
40
+ while digit_stack :
41
+
42
+ cur_value = digit_stack .pop ()
43
+
44
+ if high >= cur_value >= low :
45
+ output .append ( cur_value )
46
+
47
+ elif cur_value > high :
48
+ # current value is out of boundary
49
+ # stop growing on this case
50
+ continue
51
+
52
+ last_digit = int ( str (cur_value )[- 1 ] )
53
+
54
+ if last_digit == 9 :
55
+ # last digit is 9 already
56
+ # stop growing on this case
57
+ continue
58
+
59
+ growing_value = int ( str (cur_value ) + str (last_digit + 1 ) )
60
+
61
+ digit_stack .append ( growing_value )
62
+
63
+ return sorted ( output )
64
+
65
+
66
+
67
+ from collections import namedtuple
68
+ TestEntry = namedtuple ('TestEntry' , 'lowerbound upperbound' )
69
+ def test_bench ():
70
+
71
+ test_data = [
72
+ TestEntry ( lowerbound = 100 , upperbound = 300 ),
73
+ TestEntry ( lowerbound = 1000 , upperbound = 13000 ),
74
+ TestEntry ( lowerbound = 10 , upperbound = 1000000000 ),
75
+ ]
76
+
77
+ # expected output:
78
+ '''
79
+ [123, 234]
80
+ [1234, 2345, 3456, 4567, 5678, 6789, 12345]
81
+ [12, 23, 34, 45, 56, 67, 78, 89, 123, 234, 345, 456, 567, 678, 789, 1234, 2345, 3456, 4567, 5678, 6789, 12345, 23456, 34567, 45678, 56789, 123456, 234567, 345678, 456789, 1234567, 2345678, 3456789, 12345678, 23456789, 123456789]
82
+ '''
83
+
84
+
85
+ for t in test_data :
86
+
87
+ print ( Solution ().sequentialDigits ( low = t .lowerbound , high = t .upperbound ) )
88
+
89
+ return
90
+
91
+
92
+
93
+ if __name__ == '__main__' :
94
+
95
+ test_bench ()
0 commit comments