Weirdest solution you can find - Stack + Linear Search (in order)
x[i] is the list of indices for which arr[i] is the next greater element\nx[i] is sorted in increasing order of arr[index], where index is an element of x[i]\nf
x[i] is the list of indices for which arr[i] is the next greater element\nx[i] is sorted in increasing order of arr[index], where index is an element of x[i]\nfor every i, we calculate the next greater element of each x[i][index] after i, as x[i] is sorted, ans[x[i][index]] <= ans[x[i][index+1]] next greater element for a greater element can be the same as the answer for a smaller value or more\n```\nclass Solution {\n    public int[] secondGreaterElement(int[] arr) {\n        List<Integer>[] x = nexGreater(arr.length, arr);\n        int[] ans = new int[arr.length];\n        Arrays.fill(ans, -1);\n        for(int i = 0; i < x.length; i++) {\n            if(x[i] == null) continue;\n            int idx = 0, j = i+1;\n            while(idx < x[i].size() && j < arr.length) {\n                if(arr[j] > arr[x[i].get(idx)]) ans[x[i].get(idx++)] = arr[j];\n                else j++;\n            }\n        }\n        return ans;\n    }\n    List<Integer>[] nexGreater(int n, int arr[]) {\n        List<Integer>[] x = new List[n];\n        Stack<Integer> stack = new Stack<>();\n        for (int i = 0; i < n; i++) {\n            if (stack.isEmpty()) {\n                stack.push(i);\n                continue;\n            }\n            while (!stack.isEmpty() && arr[i] > arr[stack.peek()]) {\n                if(x[i] == null) x[i] = new ArrayList<>();\n                x[i].add(stack.pop());\n            }\n            stack.push(i);\n        }\n        return x;\n    }\n}\n```
[]