Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to generate first n lexicographic numbers in python
Lexicographic ordering sorts numbers as strings rather than numeric values. For example, "10" comes before "2" because the first character '1' comes before '2' in dictionary order.
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]
Algorithm Steps
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
Implementation
Here's the implementation using the depth-first search approach ?
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))
[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]
Alternative Approach Using Built-in Sorting
A simpler approach is to convert numbers to strings and sort them lexicographically ?
def lexicographic_numbers(n):
numbers = list(range(1, n + 1))
# Sort by string representation
return sorted(numbers, key=str)
n = 15
result = lexicographic_numbers(n)
print(result)
[1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]
How It Works
The DFS approach simulates traversing a trie structure where each node represents a digit. It explores deeper levels (adding digits) before moving to siblings. When we reach a number greater than n, we backtrack and increment.
The sorting approach leverages Python's string comparison which naturally follows lexicographic order.
Conclusion
Both approaches generate lexicographically ordered numbers efficiently. The DFS method is more space-efficient for large ranges, while the sorting method is simpler to understand and implement.
