Skip to content

Commit e85ac05

Browse files
Merge pull request #150 from nik132-eng/patch-3
Create NextGreaterElement.java
2 parents 69b1dd0 + f0f589c commit e85ac05

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

LeetCode/NextGreaterElement.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
//Given a positive integer n, find the smallest integer which has exactly
2+
//the same digits existing in the integer n and is greater in value than n.
3+
//If no such positive integer exists, return -1.
4+
5+
//Note that the returned integer should fit in 32-bit integer,
6+
//if there is a valid answer but it does not fit in 32-bit integer, return -1.
7+
8+
//Example 1:
9+
10+
//Input: n = 12
11+
//Output: 21
12+
13+
//Example 2:
14+
15+
//Input: n = 21
16+
//Output: -1
17+
18+
import java.util.Scanner;
19+
20+
public class NextGreaterElement {
21+
22+
public static void main(String[] args) {
23+
Scanner sc = new Scanner(System.in);
24+
25+
int n = sc.nextInt();
26+
long ans = nextGreaterElement(n);
27+
System.out.println(ans);
28+
}
29+
30+
private static long nextGreaterElement(int n) {
31+
// convert interger to string and than string to character array
32+
char arr[] = (Integer.toString(n)).toCharArray();
33+
34+
// firstly find first lower element from left
35+
int i = arr.length-2;
36+
while(i>=0 && arr[i]>=arr[i+1])
37+
i--;
38+
// according top test case returning the -1
39+
if(i==-1)
40+
return -1;
41+
42+
int k = arr.length-1;
43+
while(arr[i]>=arr[k])
44+
k--;
45+
// swap the values of ith and kth
46+
char temp = arr[i];
47+
arr[i] = arr[k];
48+
arr[k] = temp;
49+
50+
// Storing the values of 0 to i in res
51+
String res = "";
52+
for(int j=0;j<=i;j++)
53+
res+=arr[j];
54+
// for nearest greater integer store it in the reverse order
55+
for(int j=arr.length-1;j>i;j--)
56+
res+=arr[j];
57+
58+
59+
// typecast to Long
60+
long ans = Long.parseLong(res);
61+
if(ans<=2147483647)
62+
return (int) ans;
63+
else
64+
return -1;
65+
66+
}
67+
68+
}

0 commit comments

Comments
 (0)