386. Lexicographical Numbers LeetCode Solution

In this guide, you will get 386. Lexicographical Numbers LeetCode Solution with the best time and space complexity. The solution to Lexicographical Numbers problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Lexicographical Numbers solution in C++
  4. Lexicographical Numbers solution in Java
  5. Lexicographical Numbers solution in Python
  6. Additional Resources
386. Lexicographical Numbers LeetCode Solution image

Problem Statement of Lexicographical Numbers

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
You must write an algorithm that runs in O(n) time and uses O(1) extra space.

Example 1:
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Example 2:
Input: n = 2
Output: [1,2]

Constraints:

1 <= n <= 5 * 104

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

386. Lexicographical Numbers LeetCode Solution in C++

class Solution {
 public:
  vector<int> lexicalOrder(int n) {
    vector<int> ans;
    int curr = 1;

    while (ans.size() < n) {
      ans.push_back(curr);
      if (curr * 10 <= n) {
        curr *= 10;
      } else {
        while (curr % 10 == 9 || curr == n)
          curr /= 10;
        ++curr;
      }
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

386. Lexicographical Numbers LeetCode Solution in Java

class Solution {
  public List<Integer> lexicalOrder(int n) {
    List<Integer> ans = new ArrayList<>();
    int curr = 1;

    while (ans.size() < n) {
      ans.add(curr);
      if (curr * 10 <= n) {
        curr *= 10;
      } else {
        while (curr % 10 == 9 || curr == n)
          curr /= 10;
        ++curr;
      }
    }

    return ans;
  }
}
// code provided by PROGIEZ

386. Lexicographical Numbers LeetCode Solution in Python

class Solution:
  def lexicalOrder(self, n: int) -> list[int]:
    ans = []
    curr = 1

    while len(ans) < n:
      ans.append(curr)
      if curr * 10 <= n:
        curr *= 10
      else:
        while curr % 10 == 9 or curr == n:
          curr //= 10
        curr += 1

    return ans
# code by PROGIEZ

Additional Resources

See also  705. Design HashSet LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.