{"id":7755,"date":"2025-07-10T23:41:53","date_gmt":"2025-07-10T18:11:53","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7755"},"modified":"2025-07-10T23:43:22","modified_gmt":"2025-07-10T18:13:22","slug":"next-greater-element","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/next-greater-element\/","title":{"rendered":"Next Greater Element"},"content":{"rendered":"\n<!-- Next Greater Element I -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n  .wp_blog_theme {\n    --primary: #e58c32;\n    --secondary: #f8c291;\n    --light-bg: #fef9f4;\n    --text-dark: #2d2d2d;\n    --tab-radius: 12px;\n    --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n    --code-bg: #001f3f;\n    --code-text: #d4f1ff;\n  }\n\n  .wp_blog_container {\n    font-family: 'Segoe UI', sans-serif;\n    background: var(--light-bg);\n    margin: 0;\n    padding: 0;\n    color: var(--text-dark);\n  }\n    \/* Heading *\/\n    .wp_blog_main-heading {\n        text-align: center;\n        font-size: 2.4rem;\n        color: var(--primary);\n        margin-top: 2.5rem;\n        font-weight: bold;\n    }\n\n    \/* Explanation Card *\/\n    .wp_blog_explanation,\n    .wp_blog_code-tabs-container {\n        max-width: 940px;\n        margin: 2rem auto;\n        padding: 2rem;\n        background: white;\n        border-radius: var(--tab-radius);\n        box-shadow: var(--shadow);\n    }\n\n    \/* Text and Visuals *\/\n    .wp_blog_explanation h2 {\n        font-size: 1.4rem;\n        color: var(--primary);\n        margin-bottom: 0.5rem;\n    }\n    .wp_blog_explanation p,\n    .wp_blog_explanation li {\n        font-size: 1.05rem;\n        line-height: 1.7;\n        margin: 0.5rem 0;\n    }\n    .wp_blog_explanation code {\n        background: #fef9f4;\n        padding: 3px 6px;\n        border-radius: 4px;\n        font-family: \"Courier New\", monospace;\n    }\n    .wp_blog_explanation img {\n        max-width: 100%;\n        border-radius: var(--tab-radius);\n        margin-top: 1rem;\n        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n    }\n\n    \/* Tab Buttons *\/\n    .wp_blog_code-tabs-header {\n        display: flex;\n        flex-wrap: wrap;\n        gap: 0.5rem;\n        margin-bottom: 1rem;\n    }\n    .wp_blog_code-tab-button {\n        padding: 0.6rem 1.2rem;\n        border: 1px solid var(--primary);\n        background: white;\n        color: var(--primary);\n        border-radius: 50px;\n        font-weight: 600;\n        cursor: pointer;\n        transition: all 0.3s ease;\n    }\n    .wp_blog_code-tab-button:hover {\n        background: var(--secondary);\n    }\n    .wp_blog_code-tab-button.active {\n        background: var(--primary);\n        color: white;\n    }\n\n    \/* Code Content *\/\n    .wp_blog_code-tab-content {\n        display: none;\n        background: var(--code-bg);\n        border-radius: var(--tab-radius);\n    }\n    .wp_blog_code-tab-content.active {\n        display: block;\n    }\n    .wp_blog_code-tab-content pre {\n        margin: 0;\n        padding: 1.5rem;\n        font-size: 1rem;\n        overflow-x: auto;\n        background: var(--code-bg);\n        border-radius: var(--tab-radius);\n        color: var(--code-text);\n    }\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n<h1 class=\"wp_blog_main-heading\"><\/h1>\n\n<div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n    <p>\n        The <strong>next greater element<\/strong> of some element x in an array is the <strong>first greater<\/strong> element that is <strong>to the right<\/strong> of x in the same array.\n    <\/p>\n\n    <p>You are given two <strong>distinct 0-indexed<\/strong> integer arrays <code>nums1<\/code> and <code>nums2<\/code>, where <code>nums1<\/code> is a subset of <code>nums2<\/code>.<\/p>\n    \n   <p>\n        For each <code>0 <= i < nums1.length<\/code>, find the index <code>j<\/code> such that <code>nums1[i] == nums2[j]<\/code> and determine the <strong>next greater element<\/strong> of <code>nums2[j]<\/code> in <code>nums2<\/code>. If there is no next greater element, then the answer for this query is <code>-1<\/code>.\n   <\/p>\n\n   <p>\n        Return an array ans of length <code>nums1.length<\/code> such that <code>ans[i]<\/code> is the <strong>next greater element<\/strong> as described above.\n   <\/p>\n\n    <h2>Examples:<\/h2>\n    <p><strong>Example 1:<\/strong><\/p>\n    <p><strong>Input:<\/strong><\/p>\n        <p>nums1 = [4,1,2], nums2 = [1,3,4,2]<\/p>\n    <p><strong>Output:<\/strong><code>[-1,3,-1]<\/code><\/p>\n    <p><strong>Explanation<\/strong><\/p>\n    <p>\n        The next greater element for each value of nums1 is as follows:\n        - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n        - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n        - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n    <\/p>\n\n    <p><strong>Example 2:<\/strong><\/p>\n    <p><strong>Input:<\/strong><\/p>\n        <p>nums1 = [2,4], nums2 = [1,2,3,4]<\/p>\n    <p><strong>Output:<\/strong><code>[3,-1]<\/code><\/p>\n    <p><strong>Explanation<\/strong><\/p>\n    <p>\n        The next greater element for each value of nums1 is as follows:\n        - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n        - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.\n    <\/p>\n\n    <h2>Constraints:<\/h2>\n    <ul>\n        <li><code>1 <= nums1.length <= nums2.length <= 1000<\/code><\/li>\n        <li><code>0 <= nums1[i], nums2[i] <= 10<sup>4<\/sup><\/code><\/li>\n        <li>All integers in <code>nums1<\/code> and <code>nums2<\/code> are <strong>unique<\/strong>.<\/li>\n    <\/ul>\n\n    <h2>Approach:<\/h2>\n    <ul>\n        <li>Initialize an empty map to store each element\u2019s next greater in <code>nums2<\/code><\/li>\n        <li>Use a stack to process <code>nums2<\/code> from right to left.<\/li>\n        <li>For each element:\n            <ul>\n                <li>Pop smaller elements from the stack (they can't be NGE).<\/li>\n                <li>If stack has a greater element, that\u2019s the NGE.<\/li>\n                <li>If not, NGE is -1.<\/li>\n                <li>Push current element onto the stack.<\/li>\n            <\/ul>\n        <\/li>\n        <li><strong>Build the answer<\/strong> by mapping elements from <code>nums1<\/code> using the precomputed values from the map.<\/li>\n        <li>Return the result array.<\/li>\n    <\/ul>\n\n    <h2>Visualisation:<\/h2>\n    <img decoding=\"async\"\n        src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-10-at-11.34.07\u202fPM.png\"\n        alt=\"stack\"\n    \/>\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n + m)<\/strong> \n                <\/li> \n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(n)<\/strong> \n                <\/p>\n                <\/li>\n\n<h2>Dry Run<\/h2>\n<div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\">\n  <p><strong>Input:<\/strong><\/p>\n  <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\">\nnums1 = [4, 1, 2]\nnums2 = [1, 3, 4, 2]\n  <\/pre>\n  \n  <p><strong>State Transitions:<\/strong><\/p>\n  <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\">\nInitialize: stack = []\nn = 4 \u2192 arr = [1, 3, 4, 2]\n\nPush arr[3] = 2 onto stack\nstack = [2]\nngeMap[2] = -1\n\ni = 2 \u2192 arr[2] = 4\n\u2192 top = stack[stack.length-1] = 2\n\u2192 4 > 2 \u2192 pop 2 \u2192 stack = []\n\u2192 stack empty \u2192 ngeMap[4] = -1\n\u2192 push 4 \u2192 stack = [4]\n\ni = 1 \u2192 arr[1] = 3\n\u2192 top = 4\n\u2192 3 < 4 \u2192 ngeMap[3] = 4\n\u2192 push 3 \u2192 stack = [4, 3]\n\ni = 0 \u2192 arr[0] = 1\n\u2192 top = 3\n\u2192 1 < 3 \u2192 ngeMap[1] = 3\n\u2192 push 1 \u2192 stack = [4, 3, 1]\n\nFinal ngeMap = {\n  2: -1,\n  4: -1,\n  3: 4,\n  1: 3\n}\n\nBuild result from nums1 = [4, 1, 2]\n\u2192 ngeMap[4] = -1\n\u2192 ngeMap[1] = 3\n\u2192 ngeMap[2] = -1\n\u2192 ans = [-1, 3, -1]\n  <\/pre>\n\n  <p><strong>Final Output:<\/strong> <code>[-1, 3, -1]<\/code><\/p>\n  <p><strong>Final State:<\/strong> <code>stack = [4, 3, 1]<\/code><\/p>\n<\/div>\n\n<\/div>\n\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n        <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">\n            JavaScript\n        <\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n<pre><code class=\"language-javascript\">\nvar nextGreaterElement = function(nums1, arr) {\n    let ngeMap = {};\n    let stack = [];\n    let n = arr.length;\n\n    stack.push(arr[n-1]);\n    ngeMap[arr[n-1]] = -1;\n    for(let i=n-2; i>=0; i--){\n        let top = stack[stack.length-1];\n        if(arr[i] < top){\n            ngeMap[arr[i]] = top;\n        }\n        else {\n            while(stack.length) {\n                if(stack[stack.length-1] < arr[i]){\n                    stack.pop();\n                } else {\n                    ngeMap[arr[i]] = stack[stack.length-1];\n                    break;\n                }\n            }\n            if(stack.length === 0){\n                ngeMap[arr[i]] = -1;\n            }\n        }\n        stack.push(arr[i]);\n    }\n    let ans = [];\n    for(let i=0; i < nums1.length; i++){\n        ans.push(ngeMap[nums1[i]]);\n    }\n    return ans;\n};\n<\/code>\n<\/pre>\n<\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n        <pre><code class=\"language-python\">\ndef nextGreaterElement(nums1, arr):\n    ngeMap = {}\n    stack = []\n    n = len(arr)\n    stack.append(arr[n - 1])\n    ngeMap[arr[n - 1]] = -1\n    for i in range(n - 2, -1, -1):\n        top = stack[-1]\n        if arr[i] < top:\n            ngeMap[arr[i]] = top\n        else:\n            while stack:\n                if stack[-1] < arr[i]:\n                    stack.pop()\n                else:\n                    ngeMap[arr[i]] = stack[-1]\n                    break\n            if not stack:\n                ngeMap[arr[i]] = -1\n        stack.append(arr[i])\n    ans = []\n    for i in range(len(nums1)):\n        ans.append(ngeMap[nums1[i]])\n    return ans\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n        <pre><code class=\"language-java\">\nimport java.util.*;\npublic class Solution {\n    public int[] nextGreaterElement(int[] nums1, int[] arr) {\n        Map<Integer, Integer> ngeMap = new HashMap<>();\n        Stack<Integer> stack = new Stack<>();\n        int n = arr.length;\n        stack.push(arr[n - 1]);\n        ngeMap.put(arr[n - 1], -1);\n        for (int i = n - 2; i >= 0; i--) {\n            int top = stack.peek();\n            if (arr[i] < top) {\n                ngeMap.put(arr[i], top);\n            } else {\n                while (!stack.isEmpty()) {\n                    if (stack.peek() < arr[i]) {\n                        stack.pop();\n                    } else {\n                        ngeMap.put(arr[i], stack.peek());\n                        break;\n                    }\n                }\n                if (stack.isEmpty()) {\n                    ngeMap.put(arr[i], -1);\n                }\n            }\n            stack.push(arr[i]);\n        }\n        int[] ans = new int[nums1.length];\n        for (int i = 0; i < nums1.length; i++) {\n            ans[i] = ngeMap.get(nums1[i]);\n        }\n        return ans;\n    }\n}\n <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n        <pre><code class=\"language-cpp\">\n#include &lt;vector&gt;\n#include &lt;stack&gt;\n#include &lt;unordered_map&gt;\nusing namespace std;\n\nvector<int> nextGreaterElement(vector<int>& nums1, vector<int>& arr) {\n    unordered_map<int, int> ngeMap;\n    stack<int> s;\n    int n = arr.size();\n    s.push(arr[n - 1]);\n    ngeMap[arr[n - 1]] = -1;\n    for (int i = n - 2; i >= 0; i--) {\n        int top = s.top();\n        if (arr[i] < top) {\n            ngeMap[arr[i]] = top;\n        } else {\n            while (!s.empty()) {\n                if (s.top() < arr[i]) {\n                    s.pop();\n                } else {\n                    ngeMap[arr[i]] = s.top();\n                    break;\n                }\n            }\n            if (s.empty()) {\n                ngeMap[arr[i]] = -1;\n            }\n        }\n        s.push(arr[i]);\n    }\n    vector<int> ans;\n    for (int i = 0; i < nums1.size(); i++) {\n        ans.push_back(ngeMap[nums1[i]]);\n    }\n    return ans;\n}\n<\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n        <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#define MAX 10000\nint* nextGreaterElement(int* nums1, int nums1Size, int* arr, int arrSize, int* returnSize) {\n    int ngeMap[MAX];\n    int stack[MAX];\n    int top = -1;\n    for (int i = 0; i < MAX; i++) ngeMap[i] = -2;\n    stack[++top] = arr[arrSize - 1];\n    ngeMap[arr[arrSize - 1]] = -1;\n    for (int i = arrSize - 2; i >= 0; i--) {\n        int t = stack[top];\n        if (arr[i] < t) {\n            ngeMap[arr[i]] = t;\n        } else {\n            while (top >= 0) {\n                if (stack[top] < arr[i]) {\n                    top--;\n                } else {\n                    ngeMap[arr[i]] = stack[top];\n                    break;\n                }\n            }\n            if (top < 0) {\n                ngeMap[arr[i]] = -1;\n            }\n        }\n        stack[++top] = arr[i];\n    }\n    int* ans = (int*)malloc(nums1Size * sizeof(int));\n    for (int i = 0; i < nums1Size; i++) {\n        ans[i] = ngeMap[nums1[i]];\n    }\n    *returnSize = nums1Size;\n    return ans;\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n        <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\npublic class Solution {\n    public int[] NextGreaterElement(int[] nums1, int[] arr) {\n        Dictionary<int, int> ngeMap = new Dictionary<int, int>();\n        Stack<int> stack = new Stack<int>();\n        int n = arr.Length;\n        stack.Push(arr[n - 1]);\n        ngeMap[arr[n - 1]] = -1;\n        for (int i = n - 2; i >= 0; i--) {\n            int top = stack.Peek();\n            if (arr[i] < top) {\n                ngeMap[arr[i]] = top;\n            } else {\n                while (stack.Count > 0) {\n                    if (stack.Peek() < arr[i]) {\n                        stack.Pop();\n                    } else {\n                        ngeMap[arr[i]] = stack.Peek();\n                        break;\n                    }\n                }\n                if (stack.Count == 0) {\n                    ngeMap[arr[i]] = -1;\n                }\n            }\n            stack.Push(arr[i]);\n        }\n        int[] ans = new int[nums1.Length];\n        for (int i = 0; i < nums1.Length; i++) {\n            ans[i] = ngeMap[nums1[i]];\n        }\n        return ans;\n    }\n}\n  <\/code><\/pre>\n    <\/div>\n<\/div>\n<\/div>\n<script>\n    document.addEventListener(\"DOMContentLoaded\", () => {\n        const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n        const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n        buttons.forEach((button) => {\n            button.addEventListener(\"click\", () => {\n                const lang = button.getAttribute(\"data-lang\");\n                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n                button.classList.add(\"active\");\n                document\n                    .querySelector(\n                        `.wp_blog_code-tab-content[data-lang=\"${lang}\"]`\n                    )\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":["post-7755","post","type-post","status-publish","format-standard","category-algorithms-and-data-structures","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7755","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7755"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7755\/revisions"}],"predecessor-version":[{"id":7756,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7755\/revisions\/7756"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7755"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7755"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7755"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}