codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Leetcode] 386. Lexicographical Numbers #39

Open rmorabia opened 5 years ago

rmorabia commented 5 years ago

Given an integer n, return 1 - n in lexicographical order.

For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.

rmorabia commented 5 years ago
var lexicalOrder = function(n) {
  const allNumbers = []
  const finalNumbers = []
  for (let i = 1; i < n+1; i++) {
      allNumbers.push(i.toString())
  }
  allNumbers.sort()
  for (let z = 0; z < allNumbers.length; z++) {
    finalNumbers.push(Number(allNumbers[z]))
  }
  return finalNumbers
};

Time Complexity: O(n)

Pretty happy with this. This literally only took me 20 minutes and one quick Google search to confirm the Number() syntax.