107. Next Greater Element

NGE is a classic problem that involves arrays.

Basically, having an array and an element from it, e, we want to fetch the next (right-hand side) element greater than e. For example, let's assume the following array:

int[] integers = {1, 2, 3, 4, 12, 2, 1, 4};

Fetching the NGE for each element will result in the following pairs (-1 is interpreted as no element from the right-hand side is greater than the current one):

1 : 2   2 : 3   3 : 4   4 : 12   12 : -1   2 : 4   1 : 4   4 : -1

A simple solution to this problem will be looping the array for each element until a greater element is found or there are no more elements to check. If we just want to print the pairs on the screen, then we can write a trivial code such as the following:

public static void println(int[] arr) {

int nge;
int n = arr.length;

for (int i = 0; i < n; i++) {
nge = -1;
for (int j = i + 1; j < n; j++) {
if (arr[i] < arr[j]) {
nge = arr[j];
break;
}
}

System.out.println(arr[i] + " : " + nge);
}
}

Another solution relies on a stack. Mainly, we push elements in the stack until the currently processed element is greater than the top element in the stack. When this is happening, we pop that element. The solution is available in the code bundled to this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.141.115