{"id":27283,"date":"2018-01-20T20:35:37","date_gmt":"2018-01-20T15:05:37","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27283"},"modified":"2018-01-20T20:35:37","modified_gmt":"2018-01-20T15:05:37","slug":"python-algorithm-next-greater-element","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-next-greater-element\/","title":{"rendered":"Python 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>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Function to print element and NGE pair for all elements of list<br\/>def printNGE(arr):<br\/> <br\/>    for i in range(0, len(arr), 1):<br\/> <br\/>        next = -1<br\/>        for j in range(i+1, len(arr), 1):<br\/>            if arr[i] &lt; arr[j]:<br\/>                next = arr[j]<br\/>                break<br\/>             <br\/>        print(str(arr[i]) + &quot; -- &quot; + str(next))<br\/> <br\/># Driver program to test above function<br\/>arr = [11,13,21,3]<br\/>printNGE(arr)<br\/> <br\/># This code is contributed by Sunny Karira<\/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 pchild 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>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program to print next greater element using stack<br\/> <br\/># Stack Functions to be used by printNGE()<br\/>def createStack():<br\/>    stack = []<br\/>    return stack<br\/> <br\/>def isEmpty(stack):<br\/>    return len(stack) == 0<br\/> <br\/>def push(stack, x):<br\/>    stack.append(x)<br\/> <br\/>def pop(stack):<br\/>    if isEmpty(stack):<br\/>        print(&quot;Error : stack underflow&quot;)<br\/>    else:<br\/>        return stack.pop()<br\/> <br\/>&#039;&#039;&#039;prints element and NGE pair for all elements of<br\/>   arr[] &#039;&#039;&#039;<br\/>def printNGE(arr):<br\/>    s = createStack()<br\/>    element = 0<br\/>    next = 0<br\/> <br\/>    # push the first element to stack<br\/>    push(s, arr[0])<br\/> <br\/>    # iterate for rest of the elements<br\/>    for i in range(1, len(arr), 1):<br\/>        next = arr[i]<br\/> <br\/>        if isEmpty(s) == False:<br\/> <br\/>            # if stack is not empty, then pop an element from stack<br\/>            element = pop(s)<br\/> <br\/>            &#039;&#039;&#039;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 &#039;&#039;&#039;<br\/>            while element &lt; next :<br\/>                print(str(element)+ &quot; -- &quot; + str(next))<br\/>                if isEmpty(s) == True :<br\/>                    break<br\/>                element = pop(s)<br\/> <br\/>            &#039;&#039;&#039;If element is greater than next, then push<br\/>               the element back &#039;&#039;&#039;<br\/>            if  element &gt; next:<br\/>                push(s, element)<br\/> <br\/>        &#039;&#039;&#039;push next to stack so that we can find<br\/>           next greater for it &#039;&#039;&#039;<br\/>        push(s, next)<br\/> <br\/>    &#039;&#039;&#039;After iterating over the loop, the remaining<br\/>       elements in stack do not have the next greater<br\/>       element, so print -1 for them &#039;&#039;&#039;<br\/> <br\/>    while isEmpty(s) == False:<br\/>            element = pop(s)<br\/>            next = -1<br\/>            print(str(element) + &quot; -- &quot; + str(next))<br\/> <br\/># Driver program to test above functions<br\/>arr = [11, 13, 21, 3]<br\/>printNGE(arr)<br\/> <br\/># This code is contributed by Sunny Karira<\/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>Python Algorithm &#8211; Next Greater Element &#8211;  Stack &#8211; Given an array, print the Next Greater Element (NGE) for every element.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,73012,4148,79607],"tags":[81326,81327,81325,81300,81328,81299,81329,81298,81302,81301],"class_list":["post-27283","post","type-post","status-publish","format-standard","hentry","category-coding","category-data-structures","category-python","category-stack","tag-next-greater-element-i-leetcode-java","tag-next-greater-element-ii-leetcode","tag-next-greater-element-iii","tag-next-greater-element-in-array-java","tag-next-greater-element-java","tag-next-greater-element-leetcode","tag-next-greater-element-leetcode-python","tag-next-greater-element-using-stack","tag-next-greater-element-using-stack-in-java","tag-next-greater-number"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27283","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=27283"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27283\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27283"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27283"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27283"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}