Java || Two min heaps || priority queue
Just like finding next greatest element with a single priority queue we can use one more to track the elements which are going t be needing second greatest elem
Just like finding next greatest element with a single priority queue we can use one more to track the elements which are going t be needing second greatest element.\n\nTime: `O(NlogN)`, Space: `O(N)`\n\nsolution is explained through comments\n\n```\nclass Solution {\n    public int[] secondGreaterElement(int[] nums) {\n        int n = nums.length;\n        int[] ans = new int[n];\n        for(int i = 0;i<n;i++) ans[i] = -1;\n\t\t// Min heap to track the elements to be treated for the first time\n        PriorityQueue<Pair<Integer, Integer>> firstGreater = new PriorityQueue<>((a, b) -> {\n            return compare(a.getKey(), b.getKey());\n        });\n\t\t\n\t\t// Min heap to track the elements needing the second greater element\n        PriorityQueue<Pair<Integer, Integer>> secondGreater = new PriorityQueue<>((a, b) -> {\n            return compare(a.getKey(), b.getKey());\n        });\n        \n        firstGreater.add(new Pair(nums[0], 0));\n        \n        for(int i = 1;i<n;i++) {\n            // pop lesser elements than nums[i] and put answer for them as nums[i]\n            while(!secondGreater.isEmpty() && secondGreater.peek().getKey() < nums[i]) {\n                Pair<Integer, Integer> top = secondGreater.poll();\n                ans[top.getValue()] = nums[i];\n            }\n            \n            // pop lesser elements from firstGreater and push to secondGreater\n            while(!firstGreater.isEmpty() && firstGreater.peek().getKey() < nums[i]) {\n                secondGreater.add(firstGreater.poll());\n            }\n            \n            firstGreater.add(new Pair(nums[i], i));\n        }\n        \n        return ans;\n    }\n    \n    private int compare(int a, int b) {\n        return (Integer.valueOf(a)).compareTo(Integer.valueOf(b));\n    }\n}\n```
['Heap (Priority Queue)', 'Java']