BackmediumStackSwiggyPhonePe

Optimal Grid Path Engine 7 Solution

Problem Statement

Optimal Grid Path Engine 7

You are given an integer array nums of length N. Consider every contiguous sub‑array of nums. For each sub‑array, identify its minimum element and add that value to a running total. Your task is to compute the final sum of all these minima.

Input: The first line contains a single integer N (1 ≤ N ≤ 2·10⁵). The second line contains N space‑separated integers nums[i] (‑10⁹ ≤ nums[i] ≤ 10⁹).

Output: Output a single integer – the sum of the minimum values of all contiguous sub‑arrays. The result may be large; return it modulo 1,000,000,007.

The problem can be solved in linear time using a monotonic increasing stack that, for each element, determines how many sub‑arrays treat it as the minimum.

Example 1
Input
4 3 1 2 4
Output
17

Explanation: All contiguous sub‑arrays and their minima: [3] → 3 [3,1] → 1 [3,1,2] → 1 [3,1,2,4] → 1 [1] → 1 [1,2] → 1 [1,2,4] → 1 [2] → 2 [2,4] → 2 [4] → 4 Summing these minima: 3+1+1+1+1+1+1+2+2+4 = 17.

Example 2
Input
3 2 5 3
Output
17

Explanation: Sub‑arrays and minima: [2] → 2 [2,5] → 2 [2,5,3] → 2 [5] → 5 [5,3] → 3 [3] → 3 Total = 2+2+2+5+3+3 = 17.

Example 3
Input
4 1 2 3 4
Output
20

Explanation: Because the array is strictly increasing, each element is the minimum of all sub‑arrays that start at its position. - 1 is minimum in 4 sub‑arrays → 1·4 = 4 - 2 is minimum in 3 sub‑arrays → 2·3 = 6 - 3 is minimum in 2 sub‑arrays → 3·2 = 6 - 4 is minimum in 1 sub‑array → 4·1 = 4 Sum = 4+6+6+4 = 20.

Constraints

  • 1 <= N <= 2*10^5
  • -10^9 <= nums[i] <= 10^9
  • Result fits in 64‑bit signed integer; output modulo 1,000,000,007
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Optimal Grid Path Engine 7 — Problem Statement & Solution Guide

StackMediumMonotonic Stack Histogram
TimeO(N)
|
SpaceO(N)

Problem Description

Optimal Grid Path Engine 7

You are given an integer array nums of length N. Consider every contiguous sub‑array of nums. For each sub‑array, identify its minimum element and add that value to a running total. Your task is to compute the final sum of all these minima.

Input: The first line contains a single integer N (1 ≤ N ≤ 2·10⁵). The second line contains N space‑separated integers nums[i] (‑10⁹ ≤ nums[i] ≤ 10⁹).

Output: Output a single integer – the sum of the minimum values of all contiguous sub‑arrays. The result may be large; return it modulo 1,000,000,007.

The problem can be solved in linear time using a monotonic increasing stack that, for each element, determines how many sub‑arrays treat it as the minimum.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Optimal Grid Path Engine 7"

medium

WHY DOES IT MATTER?

Understanding contribution counting via monotonic stacks is a core technique for many range‑aggregation problems (sum of minima, maxima, sub‑array OR/AND, etc.). It transforms a seemingly quadratic enumeration into a linear scan, a skill that separates senior‑level problem solvers.

OPTIMIZATION CHALLENGE

The key insight is that an element’s influence is bounded by the nearest smaller elements on both sides. By pre‑computing these boundaries with a single pass stack, we avoid recomputing minima for overlapping sub‑arrays, collapsing O(N^2) work into O(N).

REAL-WORLD CONNECTION

Think of a load‑balancer that routes requests to the least‑loaded server in a sliding window of time. The stack efficiently tracks the current minimum load and how long it stays minimal, analogous to computing the total time each server remains the least loaded.

When coding, first compute left distances (previous smaller) in one pass, then right distances (next smaller‑or‑equal) in a second pass or in the same pass by storing indices. Use 64‑bit integers for the accumulator to prevent overflow.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The problem asks for the sum of the minimum element of every contiguous sub‑array. A naïve double loop enumerating all O(N^2) sub‑arrays and scanning each for its minimum leads to O(N^3) time, which is impossible for N up to 2·10^5. The optimal paradigm treats each array element independently and asks: in how many sub‑arrays does this element appear as the minimum? If we can compute that count in O(1) per element, the total sum is simply the sum over elements of (value * count). A monotonic increasing stack gives us the nearest strictly smaller element on the left and the nearest smaller‑or‑equal element on the right for every position. These boundaries define the maximal stretch where the current element remains the smallest, yielding leftDistance = i‑prevSmaller and rightDistance = nextSmallerOrEqual‑i. The product leftDistance·rightDistance is exactly the number of sub‑arrays where nums[i] is the minimum. Multiplying by nums[i] and accumulating gives the answer in linear time.

Interview Questions on This Problem

Q1How would you modify the solution if the problem asked for the sum of maximums of all sub‑arrays instead of minimums?

Replace the monotonic increasing stack with a decreasing stack to find the nearest greater element on the left and the nearest greater‑or‑equal on the right. The contribution formula stays the same, using those distances to count sub‑arrays where the element is the maximum.

Q2Can you compute the same sum using a divide‑and‑conquer approach? What would be its time complexity?

A divide‑and‑conquer can be built by recursively solving left and right halves and merging across the middle while maintaining a structure of minima. However, the merge step requires O(N) work per level, leading to O(N log N) overall, which is slower than the O(N) stack solution.

Q3Why must we treat equal elements asymmetrically (strictly smaller on one side, smaller‑or‑equal on the other) when using the stack?

Using strict inequality on one side and non‑strict on the other guarantees each sub‑array’s minimum is counted exactly once. If both sides treat equality the same way, sub‑arrays containing duplicate minima would be double‑counted, inflating the result.

Examples

Example 1

Input

4
3 1 2 4

Output

17

Explanation: All contiguous sub‑arrays and their minima: [3] → 3 [3,1] → 1 [3,1,2] → 1 [3,1,2,4] → 1 [1] → 1 [1,2] → 1 [1,2,4] → 1 [2] → 2 [2,4] → 2 [4] → 4 Summing these minima: 3+1+1+1+1+1+1+2+2+4 = 17.

Example 2

Input

3
2 5 3

Output

17

Explanation: Sub‑arrays and minima: [2] → 2 [2,5] → 2 [2,5,3] → 2 [5] → 5 [5,3] → 3 [3] → 3 Total = 2+2+2+5+3+3 = 17.

Example 3

Input

4
1 2 3 4

Output

20

Explanation: Because the array is strictly increasing, each element is the minimum of all sub‑arrays that start at its position. - 1 is minimum in 4 sub‑arrays → 1·4 = 4 - 2 is minimum in 3 sub‑arrays → 2·3 = 6 - 3 is minimum in 2 sub‑arrays → 3·2 = 6 - 4 is minimum in 1 sub‑array → 4·1 = 4 Sum = 4+6+6+4 = 20.

Constraints

  • 1 <= N <= 2*10^5
  • -10^9 <= nums[i] <= 10^9
  • Result fits in 64‑bit signed integer; output modulo 1,000,000,007

Optimal Approach & Strategy

Use a monotonic increasing stack to compute for each element the count of sub‑arrays where it is the minimum, then sum value × count in O(N) time.

Brute Force Approach

Enumerate all O(N^2) sub‑arrays and scan each to find its minimum, adding to the total.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   return sum;
}

Asked in Top Tech Interviews

SwiggyPhonePe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.