Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

The sum of the minimum of every subarray

Medium · Target 20 minutes · Stack· Type asked at

You're given an array of positive integers arr. Take the minimum of every contiguous subarray and add them all up, and return the total modulo 10⁹ + 7.

Examples

InputOutputWhy
arr = [3, 1, 2, 4]17If you write out the ten subarrays their minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1 and 1, which come to 17.
arr = [11, 81, 94, 43, 3]444
arr = [2, 2, 2]12All six subarrays have 2 as their minimum so it's 12, and this is the one I'd use to check that ties don't get counted twice.

Constraints

  • 1 ≤ n ≤ 3 × 10⁴
  • 1 ≤ arr[i] ≤ 3 × 10⁴

Hints

Hint 1

Going over every subarray is O(n²) at best. What if you asked, for each arr[i], how many subarrays it's the minimum of?

Hint 2

arr[i] is the minimum of a subarray as long as the subarray doesn't reach past the nearest smaller value on either side. So you need those two boundaries for every i.

Hint 3

A monotonic stack finds the previous smaller and the next smaller in one pass each. Then arr[i] counts (i − left) × (right − i) times. To stop equal values being counted twice, use strictly smaller on one side and smaller-or-equal on the other.

Where people lose marks

  • Using strictly smaller on both sides, which I've seen a fair bit. It counts a subarray like [2, 2] twice, so one of the two sides has to take the equal values.
  • Leaving the modulo until the very end, when the total can get to about 3 × 10⁴ × 4.5 × 10⁸ and that's well past 32 bits. You'd take it as you go or use 64-bit sums.
  • Getting the missing boundaries wrong. If there's no smaller value on the left you'd want left = −1, and if there's none on the right it's right = n.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.