Next Greater Number

You are given a string S which represents a number. You have to find the smallest number strictly greater than the given number which contains the same set of digits as of the original number i.e the frequency of each digit from 0 to 9 should be exactly the same as in the original number.

For example:
If the given string is 56789, then the next greater number is 56798. Note that although 56790 is also greater than the given number it contains 1 '0' which is not in the original number and also it does not contain the digit '8'.

Note:

The given string is non-empty.

If the answer does not exist, then return -1.

The given number does not contain any leading zeros.
Input Format:
The first line of the input contains an integer T denoting the number of test cases.

The first and the only line of each test case contains a string S representing the number.
Output Format:
The only line of output of each test case should print the number which is just greater than the given number as described above
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= len(S) <= 10^4
Time Limit: 1 sec
CodingNinjas
author
2y

Observations:
1. If all digits are sorted in descending order, then output is always “Not Possible”.
2. If all digits are sorted in ascending order, then we need to swap last two digits.
3. For other c...read more

CodingNinjas
author
2y
Greedy Implementation
  • First of all, we shall consider some base cases before moving on to the actual solution.
    • If all the digits are sorted in ascending order, then just swap the last two digits, and re...read more
Help your peers!
Add answer anonymously...
MakeMyTrip Senior QA Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter