Write a c++ code to print next greater element for every element.  Time Complexity of Brute for solution would be O(n^2). 

Example

Input 12 15 22 9 7 2 18 23 27
Output 15 22 23 18 18 18 23 27 -1

Here is sample code having time complexity O(N)  and O(N) extra memory space with the help of two stacks (one for indices and other for values).

Ref:http://stackoverflow.com/questions/24103061/need-to-find-the-next-greater-element-of-every-element-in-an-array