# Program to generate first n lexicographic numbers in python

Suppose we have a number n, we have to find first n numbers that are sorted in lexicographic sequence.

So, if the input is like n = 15, then the output will be [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]

To solve this, we will follow these steps:

• count := 1
• ans := a list with single element count
• while size of ans < n, do
• count := count * 10
• while count > n , do
• count := quotient of count / 10
• count := count + 1
• while count mod 10 is same as 0, do
• count := quotient of count / 10
• insert count at the end of ans
• return ans

Let us see the following implementation to get better understanding:

## Example Code

Live Demo

class Solution:
def solve(self, n):
count = 1
ans = [count]

while len(ans) < n:
count *= 10
while count > n:
count = count // 10
count += 1
while count % 10 == 0:
count = count // 10
ans.append(count)
return ans

ob = Solution()
n = 15
print(ob.solve(n))



## Input

15

## Output

[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]

Updated on: 25-Nov-2020

240 Views