File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* Given a number A in a form of string.You have to find the smallest number that has same set of digits as A and is greater than A.
2
+ If A is the greatest possible number with its set of digits, then return -1.
3
+ Problem Constraints
4
+ 1 <= A <= 10100000
5
+ A doesn't contain leading zeroes.
6
+ Input Format
7
+ First and only argument is an numeric string denoting the number A.
8
+ Output Format
9
+ Return a string denoting the smallest number greater than A with same set of digits , if A is the largest possible then return -1.
10
+ Example Input
11
+ Input 1:
12
+ A = "218765"
13
+ Input 2:
14
+ A = "4321"
15
+ Example Output
16
+ Output 1:
17
+ "251678"
18
+ Output 2:
19
+ "-1"
20
+ */
21
+ /* Approach: Check from back if it is in non increasing sequence once we get the point that breaks the sequence
22
+ find a digit that is just next greater than the current digit and swap it. Sort the digits after the current digit*/
23
+ #include < bits/stdc++.h>
24
+ using namespace std ;
25
+
26
+ string solve (string A) {
27
+ int pt=A.length ()-2 ;
28
+ for (; pt>=0 ; pt--)
29
+ if (A[pt]<A[pt+1 ])
30
+ break ;
31
+ if (pt==-1 )
32
+ return " -1" ;
33
+ sort (A.begin ()+pt+1 , A.end ());
34
+ int m = upper_bound (A.begin ()+pt+1 , A.end (), A[pt]) - A.begin ();
35
+ swap (A[pt], A[m]);
36
+
37
+ return A;
38
+ }
39
+
40
+ int main (){
41
+ string A = " 218765" ;
42
+ cout<<solve (A)<<endl;
43
+ string B = " 4321" ;
44
+ cout<<solve (B)<<endl;
45
+ }
You can’t perform that action at this time.
0 commit comments