githubEdit

22. Sum of Subarray Ranges

βœ… GFG solution to the Sum of Subarray Ranges problem: calculate sum of ranges across all subarrays using monotonic stack technique for optimal O(n) performance. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given an integer array arr[], the range of a subarray is defined as the difference between the largest and smallest elements within that subarray. Your task is to return the sum of the ranges of all possible subarrays in the array.

A subarray is a contiguous sequence of elements within an array. The goal is to efficiently compute this sum for potentially large arrays.

πŸ“˜ Examples

Example 1

Input: arr[] = [1, 2, 3]
Output: 4
Explanation: The 6 subarrays of arr are:
[1], range = 1 - 1 = 0
[2], range = 2 - 2 = 0
[3], range = 3 - 3 = 0
[1, 2], range = 2 - 1 = 1
[2, 3], range = 3 - 2 = 1
[1, 2, 3], range = 3 - 1 = 2
Sum of all ranges = 0 + 0 + 0 + 1 + 1 + 2 = 4

Example 2

πŸ”’ Constraints

  • $1 \le \text{arr.size()} \le 10^6$

  • $-10^9 \le \text{arr}[i] \le 10^9$

βœ… My Approach

The optimal approach uses the Monotonic Stack with Contribution Technique to efficiently calculate the sum:

Monotonic Stack Contribution Method

  1. Core Insight:

    • Range of a subarray = Maximum element - Minimum element

    • Sum of all ranges = (Sum of all maximums) - (Sum of all minimums)

    • Calculate contribution of each element as maximum and minimum separately

  2. Calculate Minimum Contributions:

    • Use monotonic increasing stack to find previous and next smaller elements

    • For each element at index j, find how many subarrays have it as minimum

    • Left count = distance to previous smaller element

    • Right count = distance to next smaller element

    • Contribution = arr[j] Γ— left_count Γ— right_count

  3. Calculate Maximum Contributions:

    • Use monotonic decreasing stack to find previous and next greater elements

    • For each element at index j, find how many subarrays have it as maximum

    • Apply same counting logic as minimum contributions

    • Contribution = arr[j] Γ— left_count Γ— right_count

  4. Final Result:

    • Subtract total minimum contributions from total maximum contributions

    • This gives the sum of ranges across all subarrays

  5. Stack Processing:

    • Process elements with dummy element at end (index n) to flush remaining stack

    • Track indices in stack for distance calculations

    • Use previous element index from stack or -1 if stack is empty

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the size of the array. Each element is pushed and popped from the stack at most once in each of the two passes (one for minimums, one for maximums), resulting in linear time complexity.

  • Expected Auxiliary Space Complexity: O(n), as we use a stack to store indices during processing. In the worst case, all elements might be stored in the stack before any are popped.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Four Arrays Contribution Method

πŸ’‘ Algorithm Steps:

  1. Compute left and right boundaries for each element as minimum.

  2. Compute left and right boundaries for each element as maximum.

  3. Calculate contribution of each element in both roles separately.

  4. Return difference between total maximum and minimum contributions.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Four linear passes with stack

  • Auxiliary Space: πŸ’Ύ O(n) - Four arrays and stack storage

βœ… Why This Approach?

  • Clear separation of min and max calculations

  • Easy to understand boundary computation

  • Similar to reference code structure

πŸ“Š 3️⃣ Separate Sum Calculation with Lambda

πŸ’‘ Algorithm Steps:

  1. Create reusable lambda function for sum calculation.

  2. Calculate sum of all subarray maximums using monotonic stack.

  3. Calculate sum of all subarray minimums using monotonic stack.

  4. Return difference between maximum sum and minimum sum.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Two linear passes with stack operations

  • Auxiliary Space: πŸ’Ύ O(n) - Stack storage for processing

βœ… Why This Approach?

  • Most compact and modular code

  • Reusable logic reduces code duplication

  • Clean functional programming style

πŸ“Š 4️⃣ Direct Contribution Without Extra Arrays

πŸ’‘ Algorithm Steps:

  1. Process array once to find minimum contributions directly.

  2. Process array again to find maximum contributions directly.

  3. Use stack to track previous smaller and greater elements on the fly.

  4. Accumulate contributions without storing intermediate arrays.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Two passes through array

  • Auxiliary Space: πŸ’Ύ O(n) - Single DP array and stack

βœ… Why This Approach?

  • Dynamic programming approach

  • Space efficient with single working array

  • Cumulative contribution tracking

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

πŸ“š Two-Pass Stack

🟒 O(n)

🟑 O(n)

πŸš€ Most efficient

🧩 Complex stack logic

πŸ”’ Four Arrays Method

🟒 O(n)

🟑 O(n)

πŸ“– Clear structure

πŸ’Ύ More space usage

🎯 Lambda Function

🟒 O(n)

🟑 O(n)

⭐ Clean and modular

πŸ”§ Functional style

πŸ’‘ DP Contribution

🟒 O(n)

🟑 O(n)

πŸŽ“ DP approach

🧩 Requires DP understanding

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Competitive programming

πŸ₯‡ Two-Pass Stack

β˜…β˜…β˜…β˜…β˜…

πŸ“– Interview/Learning

πŸ₯ˆ Four Arrays Method

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Production code

πŸ₯‰ Lambda Function

β˜…β˜…β˜…β˜…β˜…

🎯 DP practice

πŸ… DP Contribution

β˜…β˜…β˜…β˜…β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated