Array ( [0] => [1] => questions [2] => Arrays [3] => Next-greater-number ) Arrays | Next greater number | THE INQUISITIVE





Next greater number

LEVEL:Beginner

Description

Given an integer. You have to find the next greater number formed by the digits of a given number.

Input Format

First line contains a number N.

Output Format

Print the next greater number


Example 1:

Input
1234
Output
1243
Example 2:

Input
15526
Output
15562
Example 3:

Input
22634
Output
22643

oops

Login to see Discussion




Approach

Approach1: Next Permutation Algorithm

Step-i) Find the longest non-increasing suffix.
Step-ii) To find it, traverse the array until i-1 th element < ith element.
Step-iii) Mark the index as pivot where this condition fails.
Step-iv) If the suffix is the whole array, then there is no higher order permutation for the data.
Step-v) If the marked index is n-1, return doesnt exist.
Step-vi) Find the rightmost successor to the pivot.
Step-vii) Mark the successor index and swap it with our pivot.
Step-viii) Now reverse the suffix and return the answer.

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


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution