{"id":27257,"date":"2018-01-05T22:13:39","date_gmt":"2018-01-05T16:43:39","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27257"},"modified":"2018-01-05T22:13:39","modified_gmt":"2018-01-05T16:43:39","slug":"c-algorithm-next-greater-element","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-algorithm-next-greater-element\/","title":{"rendered":"C Algorithm &#8211; Next Greater Element"},"content":{"rendered":"<p>Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. <span id=\"more-8405\"><\/span>Elements for which no greater element exist, consider next greater element as -1.<\/p>\n<p>Examples:<br \/>\n<strong>a) <\/strong>For any array, rightmost element always has next greater element as -1.<br \/>\n<strong>b) <\/strong>For an array which is sorted in decreasing order, all elements have next greater element as -1.<br \/>\n<strong>c) <\/strong>For the input array [4, 5, 2, 25}, the next greater elements for each element are as follows.<\/p>\n<pre>Element       NGE\r\n   4      --&gt;   5\r\n   5      --&gt;   25\r\n   2      --&gt;   25\r\n   25     --&gt;   -1\r\n<\/pre>\n<p><strong>d)<\/strong> For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows.<\/p>\n<pre>  Element        NGE\r\n   13      --&gt;    -1\r\n   7       --&gt;     12\r\n   6       --&gt;     12\r\n   12     --&gt;     -1<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 1 (Simple)<\/strong><br \/>\nUse two loops: The outer loop picks all the elements one by one. The inner loop looks for the first greater element for the element picked by outer loop. If a greater element is found then that element is printed as next, otherwise -1 is printed.<\/p>\n<p><strong>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ Simple C program to print next greater elements<br\/>\/\/ in a given array<br\/>#include&lt;stdio.h&gt;<br\/> <br\/>\/* prints element and NGE pair for all elements of<br\/>arr[] of size n *\/<br\/>void printNGE(int arr[], int n)<br\/>{<br\/>    int next, i, j;<br\/>    for (i=0; i&lt;n; i++)<br\/>    {<br\/>        next = -1;<br\/>        for (j = i+1; j&lt;n; j++)<br\/>        {<br\/>            if (arr[i] &lt; arr[j])<br\/>            {<br\/>                next = arr[j];<br\/>                break;<br\/>            }<br\/>        }<br\/>        printf(&quot;%d -- %d\\n&quot;, arr[i], next);<br\/>    }<br\/>}<br\/> <br\/>int main()<br\/>{<br\/>    int arr[]= {11, 13, 21, 3};<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/>    printNGE(arr, n);<br\/>    getchar();<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>11 -- 13\r\n13 -- 21\r\n21 -- -1\r\n3 -- -1<\/pre>\n<p>Time Complexity: O(n^2). The worst case occurs when all elements are sorted in decreasing order.<\/p>\n[ad type=&#8221;banner&#8221;]\n<strong>Method 2 (Using Stack)<\/strong><br \/>\nThanks to <a href=\"http:\/\/www.geeksforgeeks.org\/forum\/topic\/next-greater-element#post-2686\" target=\"_blank\" rel=\"noopener\">pchild <\/a>for suggesting following approach.<br \/>\n1) Push the first element to stack.<br \/>\n2) Pick rest of the elements one by one and follow following steps in loop.<br \/>\n\u2026.a) Mark the current element as <em>next<\/em>.<br \/>\n\u2026.b) If stack is not empty, then pop an element from stack and compare it with <em>next<\/em>.<br \/>\n\u2026.c) If next is greater than the popped element, then <em>next <\/em>is the next greater element for the popped element.<br \/>\n\u2026.d) Keep popping from the stack while the popped element is smaller than <em>next<\/em>. <em>next<\/em> becomes the next greater element for all such popped elements<br \/>\n\u2026.g) If <em>next <\/em>is smaller than the popped element, then push the popped element back.<br \/>\n3) After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them.<\/p>\n<p><strong>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ A Stack based C program to find next greater element<br\/>\/\/ for all array elements.<br\/>#include&lt;stdio.h&gt;<br\/>#include&lt;stdlib.h&gt;<br\/>#define STACKSIZE 100<br\/> <br\/>\/\/ stack structure<br\/>struct stack<br\/>{<br\/>    int top;<br\/>    int items[STACKSIZE];<br\/>};<br\/> <br\/>\/\/ Stack Functions to be used by printNGE()<br\/>void push(struct stack *ps, int x)<br\/>{<br\/>    if (ps-&gt;top == STACKSIZE-1)<br\/>    {<br\/>        printf(&quot;Error: stack overflow\\n&quot;);<br\/>        getchar();<br\/>        exit(0);<br\/>    }<br\/>    else<br\/>    {<br\/>        ps-&gt;top += 1;<br\/>        int top = ps-&gt;top;<br\/>        ps-&gt;items [top] = x;<br\/>    }<br\/>}<br\/> <br\/>bool isEmpty(struct stack *ps)<br\/>{<br\/>    return (ps-&gt;top == -1)? true : false;<br\/>}<br\/> <br\/>int pop(struct stack *ps)<br\/>{<br\/>    int temp;<br\/>    if (ps-&gt;top == -1)<br\/>    {<br\/>        printf(&quot;Error: stack underflow \\n&quot;);<br\/>        getchar();<br\/>        exit(0);<br\/>    }<br\/>    else<br\/>    {<br\/>        int top = ps-&gt;top;<br\/>        temp = ps-&gt;items [top];<br\/>        ps-&gt;top -= 1;<br\/>        return temp;<br\/>    }<br\/>}<br\/> <br\/>\/* prints element and NGE pair for all elements of<br\/>arr[] of size n *\/<br\/>void printNGE(int arr[], int n)<br\/>{<br\/>    int i = 0;<br\/>    struct stack s;<br\/>    s.top = -1;<br\/>    int element, next;<br\/> <br\/>    \/* push the first element to stack *\/<br\/>    push(&amp;s, arr[0]);<br\/> <br\/>    \/\/ iterate for rest of the elements<br\/>    for (i=1; i&lt;n; i++)<br\/>    {<br\/>        next = arr[i];<br\/> <br\/>        if (isEmpty(&amp;s) == false)<br\/>        {<br\/>            \/\/ if stack is not empty, then pop an element from stack<br\/>            element = pop(&amp;s);<br\/> <br\/>            \/* If the popped element is smaller than next, then<br\/>                a) print the pair<br\/>                b) keep popping while elements are smaller and<br\/>                stack is not empty *\/<br\/>            while (element &lt; next)<br\/>            {<br\/>                printf(&quot;\\n %d --&gt; %d&quot;, element, next);<br\/>                if(isEmpty(&amp;s) == true)<br\/>                   break;<br\/>                element = pop(&amp;s);<br\/>            }<br\/> <br\/>            \/* If element is greater than next, then push<br\/>               the element back *\/<br\/>            if (element &gt; next)<br\/>                push(&amp;s, element);<br\/>        }<br\/> <br\/>        \/* push next to stack so that we can find<br\/>           next greater for it *\/<br\/>        push(&amp;s, next);<br\/>    }<br\/> <br\/>    \/* After iterating over the loop, the remaining<br\/>       elements in stack do not have the next greater<br\/>       element, so print -1 for them *\/<br\/>    while (isEmpty(&amp;s) == false)<br\/>    {<br\/>        element = pop(&amp;s);<br\/>        next = -1;<br\/>        printf(&quot;\\n %d -- %d&quot;, element, next);<br\/>    }<br\/>}<br\/> <br\/>\/* Driver program to test above functions *\/<br\/>int main()<br\/>{<br\/>    int arr[]= {11, 13, 21, 3};<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/>    printNGE(arr, n);<br\/>    getchar();<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre> 11 -- 13\r\n 13 -- 21\r\n 3 -- -1\r\n 21 -- -1\r\n<\/pre>\n<p>Time Complexity: O(n). The worst case occurs when all elements are sorted in decreasing order. If elements are sorted in decreasing order, then every element is processed at most 4 times.<br \/>\na) Initially pushed to the stack.<br \/>\nb) Popped from the stack when next element is being processed.<br \/>\nc) Pushed back to the stack because next element is smaller.<br \/>\nd) Popped from the stack in step 3 of algo.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C Algorithm &#8211; Next Greater Element &#8211; Stack &#8211; Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,79607],"tags":[81305,81307,81303,81300,81306,81299,81298,81302,81301,81304],"class_list":["post-27257","post","type-post","status-publish","format-standard","hentry","category-data-structures","category-stack","tag-next-greater-element-algorithm","tag-next-greater-element-c","tag-next-greater-element-ideserve","tag-next-greater-element-in-array-java","tag-next-greater-element-java-leetcode","tag-next-greater-element-leetcode","tag-next-greater-element-using-stack","tag-next-greater-element-using-stack-in-java","tag-next-greater-number","tag-next-smaller-element"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27257","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27257"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27257\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27257"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27257"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27257"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}