Sum of Subarray Minimums Algorithm in O(n) Time Complexity

Day - 77 Sum of Subarray Minimums The problem - Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7. Brute Force - Generate all possible subarrays, find the minimum element in each subarray, and sum them up. This gives O(n³) time complexity, O(n²) to generate subarrays and O(n) to find minimum in each. Approach Used - •) Initialize, create Stack<int[]> to store pairs of [value, index], create res[] array to store cumulative contributions at each position. •) For each index i from 0 to arr.length - 1, 1 - While stack is not empty AND stack.peek()[0] >= arr[i], pop from stack. 2 - j = stack.isEmpty() ? -1 : stack.peek()[1]. 3 - If stack is empty: res[i] = arr[i] × (i + 1) (all subarrays from start), else res[i] = res[j] + arr[i] × (i - j) (add new subarrays). 4 - Push [arr[i], i] onto stack. •) Initialize ans = 0 and MOD = 10^9 + 7, sum all values in res[] with modulo operation. •) Return result as integer Complexity - Time - O(n), each element pushed and popped from stack at most once. Space - O(n), for stack and result array. Note - By maintaining a monotonic increasing stack, we efficiently determine for each element how many subarrays it serves as the minimum. The res[] array accumulates contributions dynamically: res[i] = res[j] + arr[i] × (i - j) where j is the index of the previous smaller element. This avoids recalculating minimums for overlapping subarrays. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories