Best O(N) Solution
Approach 1\nBrute-Force\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1) \n\n# Code\n\nclass Solution {\npublic:\n    vector<int> nextGr
# Approach 1\nBrute-Force\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(1)$$ \n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        int n = nums.size();\n        vector <int> ans;\n        for (int i = 0; i < n; i++) {\n            int NGE = -1;\n            for (int j = 1; j < n; j++) {\n                int k = (i + j) % n;\n                if (nums[k] > nums[i]) {\n                    NGE = nums[k];\n                    break;\n                }\n            }\n            ans.push_back(NGE);\n        }\n        return ans;\n    }\n};\n```\n\n# Approach 2\nUsing Stack\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        int n = nums.size();\n        vector <int> ans;\n        stack <int> s;\n        for (int i = 2 * n - 1; i >= 0; i--) {\n            while (s.empty() == false && s.top() <= nums[i % n])\n                s.pop();\n            if (i < n) {\n                int NGE = s.empty() ? -1 : s.top();\n                ans.push_back(NGE);\n            }    \n            s.push(nums[i % n]);\n        }\n        reverse(ans.begin(), ans.end());\n        return ans;\n    }\n};\n```
['C++']