Given an array of integers, for each a[i] element print a[j] such that a[j] > a[i] and j>i. Also j should be as close to i as possible. For the rightmost element, value will be -1. If for any i if there is no such j, then result for that too will be -1. In simple terms, we need to print nearest greater number for each element in given array.
To keep track of the numbers which have yet not assigned greater number, we can use stack. Steps are simple.
To keep track of the numbers which have yet not assigned greater number, we can use stack. Steps are simple.
- If stack is empty, push the element on to stack.
- If stack is not empty, pop all elements from the stack which less than current element.
- Print these numbers paired with current number.
- If top of the stack is not less than current element or stack is empty, push the current element.(All the elements present in stack will be greater than current element why?)
- After scanning all elements in array, print all elements in stack paired with -1 as there is no greater element on right side of these elements.
Read full article from Algorithms and Me: Stacks : Next greater number for every elementvoid print_next_greater(int a[], int size){stack ms;int i;ms.top = -1;for(i=0; i<size; i++){if(is_empty(ms)){push(&ms, a[i]);}else{while(!is_empty(ms) && a[i] > peek(ms)){printf("(%d, %d)\n ", peek(ms), a[i]);pop(&ms);}push(&ms, a[i]);}}while(!is_empty(ms)){printf("(%d, %d)\n ", pop(&ms), -1);}}