Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created June 8, 2025 22:08
Show Gist options
  • Save Ifihan/b5a8659953cddfc111567f202e96faa5 to your computer and use it in GitHub Desktop.
Save Ifihan/b5a8659953cddfc111567f202e96faa5 to your computer and use it in GitHub Desktop.
Lexicographical Numbers

Question

Approach

I thought of the numbers as forming a tree — where each node represents a number, and its children are formed by appending digits 0 through 9. I used a pre-order traversal approach to explore this virtual tree. I started with 1, and at each step, I either moved deeper by multiplying the number by 10 or incremented to the next number. If the current number ended with 9 or the next number exceeded n, I backtracked by dividing the number until I found a valid next sibling.

Implementation

class Solution:
    def lexicalOrder(self, n: int) -> List[int]:
        res = []
        curr = 1
        for _ in range(n):
            res.append(curr)
            if curr * 10 <= n:
                curr *= 10
            else:
                while curr % 10 == 9 or curr + 1 > n:
                    curr //= 10
                curr += 1
        return res

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment