Skip to content

Instantly share code, notes, and snippets.

@ankita199
Last active July 30, 2019 08:27
Show Gist options
  • Save ankita199/5fe7963c45ad6b0ecd12a4cf58071d23 to your computer and use it in GitHub Desktop.
Save ankita199/5fe7963c45ad6b0ecd12a4cf58071d23 to your computer and use it in GitHub Desktop.
Implement a ruby method to find the next largest number with the same digits of the input number. Ex: 38276 would return 38627.
# Given a number as a char array number[], this function finds the next greater number.It modifies the same array to store the result
def findNextLargestNumber(array,n)
begin
# 1) Start from the right most digit and find the first digit that is smaller than the digit next to it.
i = n -1
loop do
break if array[i] > array[i - 1]
i = i - 1
end
# If no such digit is found, then all digits are in descending order means there cannot be a greater number with same set of digits
if (i == 0)
puts "Not possible"
else
x,min,j = array[i - 1], i,i+1
# 2) Find the smallest digit on right side of (i-1)'th digit that is greater than number[i-1]
while(j < n)
if (array[j] > x && array[j] < array[min])
min = j
end
j += 1
end
# 3) Swap the above found smallest digit with number[i-1]
array[min], array[i-1] = array[i-1], array[min]
# 4) Sort the digits after (i-1) in ascending order
result = (array.slice(0,i) + array.drop(i).sort).join()
puts "Next number with same set of digits is #{result}"
end
rescue Exception => e
puts "Exception: #{e.message}"
end
end
input_number = "38276"
number_to_ary = input_number.to_s.chars.map(&:to_i)
findNextLargestNumber(number_to_ary,number_to_ary.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment