{"id":3600,"date":"2021-11-11T17:49:11","date_gmt":"2021-11-11T12:19:11","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=3600"},"modified":"2021-11-11T17:49:12","modified_gmt":"2021-11-11T12:19:12","slug":"stock-span-problem","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/stock-span-problem\/","title":{"rendered":"Stock Span Problem"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\" style=\"max-width:400px\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"toggletwo\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><li><a href=\"#brute-force-approach\">Brute Force Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code\">C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#approach-2-stack\">Approach 2: Stack<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-implementation\">C++ Implementation<\/a><\/li><li><a href=\"#java-implementation\">Java Implementation<\/a><\/li><li><a href=\"#python-implementation\">Python Implementation<\/a><\/li><\/ul><li><a href=\"#faqs\">FAQs<\/a><\/li><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given a list of prices of a stock for <strong>N<\/strong> days. The task is to find the stack span for each day.<br><strong>Stock span<\/strong> can be defined as the number of consecutive days before the current day where the price of the stack was equal to or less than the current price.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"631\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-3653 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-1024x631.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-1024x631.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-300x185.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-768x473.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-1536x947.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-380x234.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-550x339.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-800x493.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5-1160x715.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-2-5.png 1799w\" ><\/figure>\n\n\n\n<p><strong>Examples:<\/strong><\/p>\n\n\n\n<p><strong>Input: A[] <\/strong>= [100,60,70,65,80,85]<br><strong>Output:<\/strong> [1,1,2,1,4,5]<br><strong>Explanation: <\/strong>Explained in image above.<\/p>\n\n\n\n<p><strong>Input: <\/strong>[31, 27, 14, 21, 30, 22]<br><strong>Output: <\/strong>[1, 1, 1, 2, 4, 1]\n\n\n\n<h2 id=\"brute-force-approach\">Brute Force Approach<\/h2>\n\n\n\n<p>A simple approach to solve this problem is to run two <strong>nested loops<\/strong> and for each element, find the maximum length such that all consecutive elements are smaller than the current element.<br>In case a large element is found, terminate the loop.<\/p>\n\n\n\n<h3 id=\"c-code\">C++ Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">void calculateSpan(int price[], int n, int S[]) {\n  S[0] = 1;\n  for (int i = 1; i &lt; n; i++) {\n    S[i] = 1;\n    for (int j = i - 1;\n      (j >= 0) &amp;&amp;\n      (price[i] >= price[j]); j--)\n      S[i]++;\n  }\n}<\/pre>\n\n\n\n<h3 id=\"java-code\">Java Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">static void calculateSpan(int price[], int n, int S[]) {\n  S[0] = 1;\n  for (int i = 1; i &lt; n; i++) {\n    S[i] = 1;\n    for (int j = i - 1;\n      (j >= 0) &amp;&amp; (price[i] >= price[j]); j--)\n      S[i]++;\n  }\n}<\/pre>\n\n\n\n<h3 id=\"python-code\">Python Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def calculateSpan(price, n, S):\n    S[0] = 1\n    for i in range(1, n, 1):\n        S[i] = 1\n        j = i - 1\n        while (j>= 0) and (price[i] >= price[j]) :\n                       S[i] += 1\n                       j -= 1<\/pre>\n\n\n\n<p><strong>Time Complexity:<\/strong>O(N^2), where N is total size of the array<br><strong>Space Complexity:<\/strong>O(1), as no extra space is used<\/p>\n\n\n\n<h2 id=\"approach-2-stack\">Approach 2: Stack<\/h2>\n\n\n\n<p id=\"instead-of-traversing-through-all-previous-elements-of-the-current-element-we-can-use-the--stack--data-structure-which-can-solve-the-problem-in-linear-time-the-approach-of-this-problem-is-very-similar-to--next-greater-element--but-the-indices-of-the-next-greater-element-is-stored-instead-of-the-element-itself\">Instead of traversing through all previous elements of the current element, we can use the <strong>Stack<\/strong> data structure which can solve the problem in linear time.<br>The approach of this problem is very similar to <strong>Next Greater Element. <\/strong>But, the indices of the next greater element is stored instead of the element itself.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"584\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-3654 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-1024x584.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-1024x584.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-300x171.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-768x438.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-1536x876.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-380x217.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-550x314.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-800x456.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2-1160x662.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-3-2.png 1944w\" ><\/figure>\n\n\n\n<p><strong>Algorithm<\/strong><\/p>\n\n\n\n<ul><li>Initialise an array <strong>S[0] = 1<\/strong> for day 0.<\/li><li>Initialise a stack and push the <strong>index<\/strong> of the first day into the stack.<\/li><li>Traverse a loop from <strong>1<\/strong> to <strong>N<\/strong> and for each iteration, do the following:<ul><li>If the stack is not <strong>empty<\/strong> and <strong>price <\/strong>of current element is greater than the top of stack, pop the element.<\/li><li>Else if, stack is not empty then, subtract index from <strong>S[i]<\/strong>, i.e. <strong>S[i] = i &#8211; S.top()<\/strong>.<\/li><li>Else, <strong>S[i] =\u00a0 i + 1<\/strong><\/li><\/ul><\/li><li>Push the current index <strong>i<\/strong> into the stack.<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"631\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-3655 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-1024x631.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-1024x631.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-300x185.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-768x473.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-1536x947.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-380x234.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-550x339.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-800x493.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6-1160x715.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/11\/Image-1-6.png 1799w\" ><\/figure>\n\n\n\n<h3 id=\"c-implementation\">C++ Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">void calculateSpan(int price[], int n, int S[]) {\n  stack &lt; int > st;\n  st.push(0);\n  S[0] = 1;\n  for (int i = 1; i &lt; n; i++) {\n    while (!st.empty() &amp;&amp; price[st.top()] &lt; price[i])\n      st.pop();\n \n    S[i] = (st.empty()) ? (i + 1) : (i - st.top());\n    st.push(i);\n  }\n}<\/pre>\n\n\n\n<h3 id=\"java-implementation\">Java Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">static void calculateSpan(int price[], int n, int S[]) {\n  Stack &lt; Integer > st = new Stack &lt; > ();\n  st.push(0);\n \n  S[0] = 1;\n  for (int i = 1; i &lt; n; i++) {\n    while (!st.empty() &amp;&amp; price[st.peek()] &lt;= price[i])\n      st.pop();\n \n    S[i] = (st.empty()) ? (i + 1) : (i - st.peek());\n    st.push(i);\n  }\n}<\/pre>\n\n\n\n<h3 id=\"python-implementation\">Python Implementation<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def calculateSpan(price, S):\n     \n    n = len(price)\n    st = []\n    st.append(0)\n \n    S[0] = 1\n \n    for i in range(1, n):\n        while( len(st) > 0 and price[st[-1]] &lt;= price[i]):\n            st.pop()\n \n        S[i] = i + 1 if len(st) &lt;= 0 else (i - st[-1])\n \n        st.append(i)<\/pre>\n\n\n\n<p><strong>Time Complexity:<\/strong>O(N), where N is total size of the array<br><strong>Space Complexity:<\/strong>O(1), as no extra space is used.<\/p>\n\n\n\n<p><strong>Practice Questions<\/strong><\/p>\n\n\n\n<p><a href=\"https:\/\/www.interviewbit.com\/problems\/best-time-to-buy-and-sell-stocks-i\/\" target=\"_blank\" rel=\"noreferrer noopener\">Best time to buy and sell stocks<\/a><\/p>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<p><strong>What is Stock Span Problem?<br>Stock span<\/strong> can be defined as the number of consecutive days before the current day where the price of the stack was equal to or less than the current price.<\/p>\n\n\n\n<p><strong>What is the most efficient approach to solving the stock span problem?<br><\/strong>The stack-based approach is the most efficient approach to solve the problem. The time complexity is O(N) and space complexity is O(1).<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given a list of prices of a stock for N days. The task is to find&hellip;\n","protected":false},"author":5,"featured_media":3656,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[457,558],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3600"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=3600"}],"version-history":[{"count":3,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3600\/revisions"}],"predecessor-version":[{"id":3657,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3600\/revisions\/3657"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/3656"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=3600"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=3600"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=3600"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}