Java | TreeMap
Maintain sorted map with all numbers that do not have two greater elements yet\n Iterate through all number\n\t For current element: get subMap with all the num
* Maintain sorted map with all numbers that do not have two greater elements yet\n* Iterate through all number\n\t* For current element: get subMap with all the numbers with lower value that we have already seen and have not found two greater elements\n\t* Remove numbers from the map with two greater elements\n\t* Put current number into the map\n\n```\npublic int[] secondGreaterElement(int[] nums) {\n\tvar res = new int[nums.length];\n\tArrays.fill(res, -1);\n\n\t// < val, { index, count } >\n\tvar m = new TreeMap<Integer, List<int[]>>();\n\tfor (int i = 0; i < res.length; i++) {\n\t\t// get all numbers with lower value that we have already seen and have not found two greater elements \n\t\tvar sub = new TreeMap<>(m.subMap(0, nums[i]));\n\n\t\tfor (var e : sub.entrySet()) {\n\t\t\tvar newList = new ArrayList<int[]>();\n\t\t\tfor (var v : e.getValue()) {\n\t\t\t\tif (v[1] == 1) {\n\t\t\t\t\tres[v[0]] = nums[i];\n\t\t\t\t} else {\n\t\t\t\t\tv[1] = 1;\n\t\t\t\t\tnewList.add(v);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (newList.size() == 0) {\n\t\t\t\t// clean up to reduce time complexity\n\t\t\t\tm.remove(e.getKey());\n\t\t\t} else {\n\t\t\t\t// put back list of numbers with one greater element \n\t\t\t\tm.put(e.getKey(), newList);\n\t\t\t}\n\t\t}\n\t\t// put current number\n\t\tm.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(new int[] { i, 0 });\n\t}\n\n\treturn res;\n}\n```
[]