Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1ef3296

Browse files
author
Ram swaroop
committed
next greater element : error fixed
1 parent 75d5941 commit 1ef3296

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed
Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package me.ramswaroop.arrays;
22

3-
import java.util.Arrays;
3+
import me.ramswaroop.common.LinkedStack;
4+
import me.ramswaroop.common.Stack;
45

56
/**
67
* Created by IntelliJ IDEA.
@@ -19,22 +20,41 @@ public class NextGreaterElement {
1920
* @param a
2021
* @return
2122
*/
22-
public static int[] nextGreaterElements(int[] a) {
23-
int[] greaterElements = new int[a.length]; // stores the next greater element of each element in array a
24-
greaterElements[a.length - 1] = -1; // no elements greater than the last element
23+
public static void nextGreaterElements(int[] a) {
24+
int i = 0;
25+
Stack<Integer> stack = new LinkedStack<>(); // used to store elements whose NGE is yet to be determined
2526

26-
for (int i = a.length - 2; i >= 0; i--) {
27-
if (a[i + 1] > a[i]) { // if next element is greater than the current element
28-
greaterElements[i] = a[i + 1];
29-
} else { // if next element is smaller then find the greater element of the next element
30-
greaterElements[i] = greaterElements[i + 1];
27+
for (; i < a.length - 1; i++) {
28+
stack.push(a[i]);
29+
30+
while (!stack.isEmpty()) {
31+
Integer pop = stack.pop();
32+
if (pop < a[i + 1]) { // NGE found for popped element
33+
System.out.println(pop + "->" + a[i + 1]);
34+
} else {
35+
stack.push(pop); // NGE still not found for popped element, so push it again
36+
break;
37+
}
3138
}
3239
}
33-
return greaterElements;
40+
41+
// no NGE for elements left in stack
42+
while (!stack.isEmpty()) {
43+
System.out.println(stack.pop() + "->" + -1);
44+
}
45+
46+
// no NGE for last element
47+
System.out.println(a[i] + "->" + -1);
3448
}
3549

3650
public static void main(String a[]) {
37-
System.out.println(Arrays.toString(nextGreaterElements(new int[]{4, 5, 2, 25})));
38-
System.out.println(Arrays.toString(nextGreaterElements(new int[]{11, 13, 21, 3})));
51+
int[] ar = new int[]{4, 5, 2, 25};
52+
nextGreaterElements(ar);
53+
System.out.println("=========");
54+
ar = new int[]{11, 13, 21, 3};
55+
nextGreaterElements(ar);
56+
System.out.println("=========");
57+
ar = new int[]{1, 5, 3, 4, 2, 0, 11};
58+
nextGreaterElements(ar);
3959
}
4060
}

0 commit comments

Comments
 (0)