Skip to content

Commit d2fc777

Browse files
committed
Added algorithm to generate numbers in lexicographical order
1 parent 00e9d86 commit d2fc777

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def lexicalOrder(n: int) -> str:
2+
"""
3+
Generate numbers in lexical order from 1 to n and return them as a space-separated string.
4+
5+
>>> lexicalOrder(13)
6+
'1 10 11 12 13 2 3 4 5 6 7 8 9'
7+
>>> lexicalOrder(1)
8+
'1'
9+
>>> lexicalOrder(20)
10+
'1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9'
11+
>>> lexicalOrder(25)
12+
'1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 3 4 5 6 7 8 9'
13+
"""
14+
ans = []
15+
stack = [1]
16+
17+
while stack:
18+
num = stack.pop()
19+
if num > n:
20+
continue
21+
22+
ans.append(str(num))
23+
if (num % 10) != 9:
24+
stack.append(num + 1)
25+
26+
stack.append(num * 10)
27+
28+
return " ".join(ans)
29+
30+
if __name__ == "__main__":
31+
32+
from doctest import testmod
33+
34+
testmod()
35+
print(f"Numbers from 1 to 25 in lexical order: {lexicalOrder(25)}")

0 commit comments

Comments
 (0)