{"id":900,"date":"2025-08-19T12:20:49","date_gmt":"2025-08-19T06:50:49","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=900"},"modified":"2025-08-19T12:20:51","modified_gmt":"2025-08-19T06:50:51","slug":"sum-of-subarray-minimums","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/","title":{"rendered":"Sum of Subarray Minimums | Leetcode 907 | Stack Optimal Solution"},"content":{"rendered":"\n<p>Given an array of integers arr, find the sum of&nbsp;<code>min(b)<\/code>, where&nbsp;<code>b<\/code>&nbsp;ranges over every (contiguous) subarray of&nbsp;<code>arr<\/code>. Since the answer may be large, return the answer&nbsp;<strong>modulo<\/strong>&nbsp;<code>10<sup>9<\/sup> + 7<\/code>.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/sum-of-subarray-minimums\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> arr = [3,1,2,4]<br><strong>Output:<\/strong> 17<br><strong>Explanation:<\/strong> <br>Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. <br>Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.<br>Sum is 17.<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> arr = [11,81,94,43,3]<br><strong>Output:<\/strong> 444<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= arr.length &lt;= 3 * 10<sup>4<\/sup><\/code><\/li>\n\n\n\n<li><code>1 &lt;= arr[i] &lt;= 3 * 10<sup>4<\/sup><\/code><\/li>\n<\/ul>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-e0d405f9-aaec-4ce2-a2f5-cfd39bf3e8bf\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"true\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#0-brute-force-nested-loops-\" style=\"\">Brute Force (Nested Loops)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#1-intuition-and-approach\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#2-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#4-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#5-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#6-optimal-monotonic-stack-with-plenle-\" style=\"\">Optimal (Monotonic Stack\u00a0with\u00a0PLE\/NLE)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#7-intuition\" style=\"\">Intuition<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#8-detailed-approach\" style=\"\">Detailed Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#9-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#11-time-and-space-complexity\" style=\"\">Time and Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#12-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#13-when-to-use-which\" style=\"\">When to Use Which<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/sum-of-subarray-minimums\/#14-common-pitfalls-and-tips\" style=\"\">Common Pitfalls and Tips<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-nested-loops-\">Brute Force (<strong>Nested Loops<\/strong>)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Enumerate all subarrays starting at\u00a0<code>i<\/code>\u00a0and ending at\u00a0<code>j<\/code>.<\/li>\n\n\n\n<li>Maintain\u00a0<strong>running minimum<\/strong>\u00a0for the current subarray and add it to the total.<\/li>\n\n\n\n<li>Take modulo each time to prevent overflow. This is\u00a0<strong>simple<\/strong>\u00a0and\u00a0<strong>correct<\/strong>\u00a0but not efficient for large\u00a0<code>n<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def sumSubarrayMins(self, arr: List[int]) -&gt; int:\n        total = 0\n        n = len(arr)\n        for i in range(0, n):\n            mini = float(&quot;inf&quot;)\n            for j in range(i, n):\n                # Update running minimum for subarray arr[i..j]\n                mini = min(mini, arr[j])\n                # Add current subarray's minimum\n                total = (total + mini) % (10**9 + 7)\n        return total\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">sumSubarrayMins<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        total = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            mini = <\/span><span style=\"color: #4EC9B0\">float<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #CE9178\">&quot;inf&quot;<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Update running minimum for subarray arr[i..j]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                mini = <\/span><span style=\"color: #DCDCAA\">min<\/span><span style=\"color: #D4D4D4\">(mini, arr[j])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Add current subarray&#39;s minimum<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                total = (total + mini) % (<\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">**<\/span><span style=\"color: #B5CEA8\">9<\/span><span style=\"color: #D4D4D4\"> + <\/span><span style=\"color: #B5CEA8\">7<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> total<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For each starting index\u00a0<code>i<\/code>, expand\u00a0<code>j<\/code>\u00a0to the right while tracking the current\u00a0<strong>minimum<\/strong>\u00a0<code>mini<\/code>.<\/li>\n\n\n\n<li>Each step contributes the current\u00a0<code>mini<\/code>\u00a0to the answer.<\/li>\n\n\n\n<li>Time grows\u00a0<strong>quadratically<\/strong>\u00a0due to all pairs\u00a0<code>(i, j)<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:\u00a0<strong>Time O(n^2)<\/strong>,\u00a0<strong>Space O(1)<\/strong>.<\/li>\n\n\n\n<li>Simplified:\u00a0<strong>Quadratic time<\/strong>; fine for\u00a0<strong>small arrays<\/strong>, slow for\u00a0<strong>large<\/strong>\u00a0ones.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-conclusion\">Conclusion<\/h3>\n\n\n\n<p>A great&nbsp;<strong>baseline<\/strong>&nbsp;for understanding the task, but&nbsp;<strong>not scalable<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-optimal-monotonic-stack-with-plenle-\">Optimal (<strong>Monotonic Stack<\/strong>&nbsp;with&nbsp;<strong>PLE\/NLE<\/strong>)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-intuition\">Intuition<\/h3>\n\n\n\n<p>View the sum as the sum of&nbsp;<strong>contributions<\/strong>&nbsp;of each element&nbsp;<code>arr[i]<\/code>&nbsp;as the&nbsp;<strong>minimum<\/strong>&nbsp;across all subarrays where it is the smallest. For any index&nbsp;<code>i<\/code>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Determine how many subarrays choose\u00a0<code>arr[i]<\/code>\u00a0as their\u00a0<strong>minimum<\/strong>.<\/li>\n\n\n\n<li>Let\u00a0<code>ple[i]<\/code>\u00a0be the index of the\u00a0<strong>Previous Less Element<\/strong>\u00a0(<strong>strictly less<\/strong>) to the left of\u00a0<code>i<\/code>; if none, use\u00a0<code>-1<\/code>.<\/li>\n\n\n\n<li>Let\u00a0<code>nle[i]<\/code>\u00a0be the index of the\u00a0<strong>Next Less Element<\/strong>\u00a0(<strong>less or equal<\/strong>) to the right of\u00a0<code>i<\/code>; if none, use\u00a0<code>n<\/code>.<\/li>\n\n\n\n<li>Then the count of subarrays where\u00a0<code>arr[i]<\/code>\u00a0is minimum equals:\n<ul class=\"wp-block-list\">\n<li><code>left = i \u2212 ple[i]<\/code>\u00a0choices for the left boundary<\/li>\n\n\n\n<li><code>right = nle[i] \u2212 i<\/code>\u00a0choices for the right boundary<\/li>\n\n\n\n<li>total subarrays contributed by\u00a0<code>i<\/code>\u00a0=\u00a0<code>left \u00d7 right<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Contribution of\u00a0<code>arr[i]<\/code>\u00a0=\u00a0<code>arr[i] \u00d7 left \u00d7 right<\/code>.<\/li>\n<\/ul>\n\n\n\n<p>Why&nbsp;<strong>strict vs non-strict<\/strong>?<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>To avoid\u00a0<strong>double-counting equal elements<\/strong>, define\u00a0<strong>PLE with \u201c>\u201d<\/strong>\u00a0and\u00a0<strong>NLE with \u201c>=\u201d<\/strong>. This breaks ties consistently: the \u201c<strong>next less or equal<\/strong>\u201d on the right ensures only one of equal elements takes\u00a0<strong>ownership<\/strong>\u00a0of a subarray.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-detailed-approach\">Detailed Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Compute\u00a0<strong>PLE<\/strong>\u00a0using a strictly increasing stack from\u00a0<strong>left to right<\/strong>:\n<ul class=\"wp-block-list\">\n<li>While\u00a0<code>top > arr[i]<\/code>,\u00a0<strong>pop<\/strong>.<\/li>\n\n\n\n<li><code>ple[i] =<\/code>\u00a0top index if exists, else\u00a0<code>-1<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Compute\u00a0<strong>NLE<\/strong>\u00a0using a non-decreasing stack from\u00a0<strong>right to left<\/strong>:\n<ul class=\"wp-block-list\">\n<li>While\u00a0<code>top >= arr[i]<\/code>,\u00a0<strong>pop<\/strong>.<\/li>\n\n\n\n<li><code>nle[i] =<\/code>\u00a0top index if exists, else\u00a0<code>n<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Sum contributions:\u00a0<code>arr[i] \u00d7 (i \u2212 ple[i]) \u00d7 (nle[i] \u2212 i)<\/code>, mod\u00a0<strong>1e9+7<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def sumSubarrayMins(self, arr):\n        MOD = 10**9 + 7\n        n = len(arr)\n        stack = []\n        ple = [-1] * n  # Previous Less Element index\n        nle = [n] * n   # Next Less Element index\n\n        # Previous Less Element (strictly less)\n        for i in range(n):\n            while stack and arr[stack[-1]] &gt; arr[i]:\n                stack.pop()\n            ple[i] = stack[-1] if stack else -1\n            stack.append(i)\n\n        # Reset stack\n        stack = []\n\n        # Next Less Element (less or equal)\n        for i in range(n - 1, -1, -1):\n            while stack and arr[stack[-1]] &gt;= arr[i]:\n                stack.pop()\n            nle[i] = stack[-1] if stack else n\n            stack.append(i)\n\n        # Calculate result by contribution\n        result = 0\n        for i in range(n):\n            left = i - ple[i]\n            right = nle[i] - i\n            result = (result + arr[i] * left * right) % MOD\n\n        return result\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">sumSubarrayMins<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">arr<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        MOD = <\/span><span style=\"color: #B5CEA8\">10<\/span><span style=\"color: #D4D4D4\">**<\/span><span style=\"color: #B5CEA8\">9<\/span><span style=\"color: #D4D4D4\"> + <\/span><span style=\"color: #B5CEA8\">7<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(arr)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        stack = []<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ple = [-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] * n  <\/span><span style=\"color: #6A9955\"># Previous Less Element index<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        nle = [n] * n   <\/span><span style=\"color: #6A9955\"># Next Less Element index<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Previous Less Element (strictly less)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> stack <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr[stack[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]] &gt; arr[i]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                stack.pop()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            ple[i] = stack[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> stack <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\"> -<\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            stack.append(i)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Reset stack<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        stack = []<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Next Less Element (less or equal)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> stack <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> arr[stack[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]] &gt;= arr[i]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                stack.pop()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            nle[i] = stack[-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">] <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> stack <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\"> n<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            stack.append(i)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Calculate result by contribution<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        result = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            left = i - ple[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            right = nle[i] - i<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            result = (result + arr[i] * left * right) % MOD<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> result<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The first pass builds\u00a0<strong>PLE<\/strong>\u00a0using a\u00a0<strong>monotonic increasing stack<\/strong>\u00a0(values strictly increasing by indices): popping when a\u00a0<strong>strictly greater<\/strong>\u00a0value is found ensures\u00a0<code>ple[i]<\/code>\u00a0holds the\u00a0<strong>nearest smaller<\/strong>\u00a0element.<\/li>\n\n\n\n<li>The second pass builds\u00a0<strong>NLE<\/strong>\u00a0using a monotonic stack with \u201c<strong>>=<\/strong>\u201d popping to handle\u00a0<strong>duplicates<\/strong>\u00a0correctly and ensure a\u00a0<strong>unique owner<\/strong>\u00a0for tied values.<\/li>\n\n\n\n<li>The final loop aggregates each element\u2019s\u00a0<strong>contribution<\/strong>\u00a0under\u00a0<strong>modulo<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-time-and-space-complexity\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:\u00a0<strong>Time O(n)<\/strong>\u00a0(each index pushed\/popped at most once per pass),\u00a0<strong>Space O(n)<\/strong>\u00a0for stacks and arrays.<\/li>\n\n\n\n<li>Simplified:\u00a0<strong>Linear time<\/strong>\u00a0and\u00a0<strong>space<\/strong>; ideal for\u00a0<strong>large inputs<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-conclusion\">Conclusion<\/h3>\n\n\n\n<p>The&nbsp;<strong>monotonic stack<\/strong>&nbsp;solution transforms a&nbsp;<strong>quadratic<\/strong>&nbsp;enumeration into an elegant&nbsp;<strong>linear-time<\/strong>&nbsp;contribution sum. The choice of&nbsp;<strong>strict vs non-strict<\/strong>&nbsp;comparisons is&nbsp;<strong>crucial<\/strong>&nbsp;to avoid&nbsp;<strong>double-counting<\/strong>&nbsp;with&nbsp;<strong>duplicates<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"13-when-to-use-which\">When to Use Which<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the\u00a0<strong>Brute Force<\/strong>\u00a0method for\u00a0<strong>learning<\/strong>\u00a0and\u00a0<strong>tiny inputs<\/strong>.<\/li>\n\n\n\n<li>Use the\u00a0<strong>Monotonic Stack (PLE\/NLE)<\/strong>\u00a0method for\u00a0<strong>production-grade efficiency<\/strong>\u00a0with\u00a0<strong>O(n)<\/strong>\u00a0time.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"14-common-pitfalls-and-tips\">Common Pitfalls and Tips<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Be mindful of\u00a0<strong>tie-breaking<\/strong>: use\u00a0<strong>\u201c>\u201d<\/strong>\u00a0for\u00a0<strong>PLE<\/strong>\u00a0and\u00a0<strong>\u201c>=\u201d<\/strong>\u00a0for\u00a0<strong>NLE<\/strong>.<\/li>\n\n\n\n<li>Always apply\u00a0<strong>modulo<\/strong>\u00a0at each accumulation to prevent\u00a0<strong>overflow<\/strong>.<\/li>\n\n\n\n<li>Test with\u00a0<strong>duplicates-heavy<\/strong>\u00a0arrays (e.g., &#8220;) to validate\u00a0<strong>tie-handling<\/strong>.<a href=\"https:\/\/leetcode.com\/problems\/sum-of-subarray-minimums\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given an array of integers arr, find the sum of&nbsp;min(b), where&nbsp;b&nbsp;ranges over every (contiguous) subarray of&nbsp;arr. Since the answer may be large, return the answer&nbsp;modulo&nbsp;109 + 7. Here&#8217;s the [Problem Link] to begin with. Example 1: Input: arr = [3,1,2,4]Output: 17Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. Minimums are<\/p>\n","protected":false},"author":1,"featured_media":902,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[19,37],"class_list":{"0":"post-900","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-medium","10":"tag-stack-and-queues"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/sum-of-subarray-minimums-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/900","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=900"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/900\/revisions"}],"predecessor-version":[{"id":903,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/900\/revisions\/903"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/902"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=900"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=900"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=900"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}