k-th greater element
We will take a look at a generic solution that can find k-th greater element.\n\nWe will reuse the next greater element algorithm almost "as-is".\n> As a quick 
We will take a look at a generic solution that can find `k`-th greater element.\n\nWe will reuse the next greater element algorithm almost "as-is".\n> As a quick refresher, that algorithm goes right-to-left maintaining a mono-stack, and binary-searches the monostack to find the next greater element.\n\nSay, `nums[i]` is the next greater element for previous elements `nums[j0], nums[j1], ...`. During the first pass, we will track indexes of those elements in `prev[j]`.\n\nDuring the second pass, when we reach `nums[i]`, we will search the monostrack for the next greater element for `nums[j0], nums[j1], ...`. Again, we will link that greater elements to indexes of previous elements.\n\nTherefore, after the second pass, for each index `j` in `prev[i]`, `nums[i]` is the second greater element for `nums[j]`.\n\n![image](https://assets.leetcode.com/users/images/27bfcc2d-5bfc-4fec-b749-170d554998fa_1667072187.056245.png)\n\nWe can do one more pass to figure out the third greater element, and so on.\n\n**C++**\n```cpp\nvector<vector<int>> greaterElement(vector<int>& nums, const vector<vector<int>> &prev) {\n    vector<int> ms;\n    vector<vector<int>> pprev(nums.size());\n    for (int i = nums.size() - 1; i >= 0; --i) {\n        for (int j : prev.empty() ? vector<int>{i} : prev[i]) {\n            auto it = upper_bound(rbegin(ms), rend(ms), j, [&](int i, int j){ return nums[i] < nums[j]; });\n            if (it != rend(ms))\n                pprev[*it].push_back(j);\n        }\n        while(!ms.empty() && nums[ms.back()] < nums[i])\n            ms.pop_back();\n        ms.push_back(i);\n    }\n    return pprev;\n}\nvector<int> secondGreaterElement(vector<int>& nums, int k = 2) {\n    vector<int> res(nums.size(), -1);\n    vector<vector<int>> prev;\n    while (--k >= 0)\n        prev = greaterElement(nums, prev);\n    for (int i = nums.size() - 1; i >= 0; --i)\n        for (int j : prev[i])\n            res[j] = nums[i];\n    return res;\n}\n```
['C']