Sum of Subarray Minimums

Stack / Queues Monotonic Stack Medium
  • This problem highlights and tests understanding in array manipulation and dynamic programming, which are essential concepts used in a variety of fields in the software industry
  • For instance, efficient array manipulation like calculating sums of subarrays can be found at the core of data processing libraries used in data analysis and machine learning, such as NumPy and Pandas in Python
  • Similarly, understanding of subarray computations is also useful in developing efficient algorithms in computer graphics for operations such as image cropping and rotation
  • This problem's requirement to return the answer modulus a large number is a common technique used when dealing with very large numbers to prevent arithmetic overflow, which is an essential consideration in fields ranging from cryptography to scientific computing

Given an array of integers arr of size n, calculate the sum of the minimum value in each (contiguous) subarray of arr. Since the result may be large, return the answer modulo 109 +7.

Examples:

Input: arr = [3, 1, 2, 5]

Output: 18

Explanation: The minimum of subarrays: [3], [1], [2], [5], [3, 1], [1, 2], [2, 5], [3, 1, 2], [1, 2, 5], [3, 1, 2, 5] are 3, 1, 2, 5, 1, 1, 2, 1, 1, 1 respectively and their sum is 18.

Input: arr = [2, 3, 1]

Output: 10

Explanation: The minimum of subarrays: [2], [3], [1], [2,3], [3,1], [2,3,1] are 2, 3, 1, 2, 1, 1 respectively and their sum is 10.

Input: arr = [11, 81, 94, 43, 3]

Constraints

  •   1 <= arr.length <= 105
  •   1 <= arr[i] <= 106

Hints

  • Instead of generating all subarrays, count how many times each element is the minimum in different subarrays. Use a monotonic increasing stack to determine for each element.
  • Traverse left to right using a monotonic increasing stack to compute L[i]. Traverse right to left using a monotonic increasing stack to compute R[i].

Company Tags

Cerner Micron Technology Alibaba Etsy Stripe Splunk Epic Systems Mastercard Rakuten Byju's Reddit Nutanix Texas Instruments Walmart Johnson & Johnson PwC Twilio Epic Games Roblox Boston Consulting Group Unity Technologies Ernst & Young Siemens Healthineers eBay Swiggy Google Microsoft Amazon Meta Apple Netflix Adobe