So, recently I was checking one of a coding challenge. The problem was quite intriguing so just want to know whether there is a better way to do it in terms of time and space complexity. 

Problem: Given a number x where x will be positive number > 0. Find the nearest smallest number with the same number of digits. If it exists so return the smallest number otherwise print "Nearest Smallest Number doesn't exist". What I mean by **same number of digits** is if the number is 12345 so with these number of digits(In this case the number of digits is 5) so you can't find the nearest smaller number. Although you can say it can be 1234 but it is not the same number of digits. You need to make **use of all the digits** when finding the nearest smallest number

So, below are a few examples

Number: 8563
Output: 8536

Number 7385
output 7358

Number: 3857
Output: 3785

Number: 123
Output: Nearest Smallest Number doesn't exist

```
number = gets.to_i
flag = 1
numbers_array =  number.digits.permutation(Math.log10(number).to_i + 1).sort
numbers_array.each_with_index do |e, index| 
  if e.join.to_i == number
    print numbers_array[index - 1]
    flag = 0
    break
  end
end
if flag == 1
  puts "Nearest Smallest Number not exist"
end

```

Note: The above solution will take more time when the number will be very big