Sum of Total Strength of Wizards - Problem

As the ruler of a kingdom, you have an army of wizards at your command.

You are given a 0-indexed integer array strength, where strength[i] denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength), the total strength is defined as the product of the following two values:

  • The strength of the weakest wizard in the group.
  • The sum of all the individual strengths of the wizards in the group.

Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 109 + 7.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: strength = [1,3,1,2]
Output: 44
💡 Note: All subarrays: [1]=1×1=1, [1,3]=1×4=4, [1,3,1]=1×5=5, [1,3,1,2]=1×7=7, [3]=3×3=9, [3,1]=1×4=4, [3,1,2]=1×6=6, [1]=1×1=1, [1,2]=1×3=3, [2]=2×2=4. Total = 1+4+5+7+9+4+6+1+3+4 = 44
Example 2 — Single Element
$ Input: strength = [5]
Output: 25
💡 Note: Only one subarray [5]: minimum=5, sum=5, total strength = 5×5 = 25
Example 3 — Ascending Order
$ Input: strength = [1,2,3]
Output: 33
💡 Note: [1]=1×1=1, [1,2]=1×3=3, [1,2,3]=1×6=6, [2]=2×2=4, [2,3]=2×5=10, [3]=3×3=9. Total = 1+3+6+4+10+9 = 33

Constraints

  • 1 ≤ strength.length ≤ 105
  • 1 ≤ strength[i] ≤ 109

Visualization

Tap to expand
Sum of Total Strength of Wizards INPUT strength[] array 1 i=0 3 i=1 1 i=2 2 i=3 W W W W Example Subarrays: [1] --> min=1, sum=1 [3] --> min=3, sum=3 [1,3] --> min=1, sum=4 [3,1] --> min=1, sum=4 [1,3,1] --> min=1, sum=5 ... and more Total = min * sum for each subarray ALGORITHM STEPS 1 Build Prefix Sums prefix[i] = sum of strength[0..i] prefix_prefix for range sums 2 Monotonic Stack Find left/right boundaries where each elem is minimum Stack idx: 0 idx: 2 3 Calculate Contribution For each wizard as minimum: contribution = str[i] * (sum of all valid subarrays) 4 Sum All Contributions Total = sum of all wizard contributions Apply mod 10^9 + 7 FINAL RESULT All Subarray Contributions: [1]: 1*1 = 1 [3]: 3*3 = 9 [1]: 1*1 = 1 [2]: 2*2 = 4 [1,3]: 1*4 = 4 [3,1]: 1*4 = 4 [1,2]: 1*3 = 3 [1,3,1]: 1*5 = 5 [3,1,2]: 1*6 = 6 [1,3,1,2]: 1*7 = 7 Total: 1+9+1+4+4+4+3+5+6+7 Output: 42 OK Key Insight: Use a monotonic stack to find the range where each element is the minimum in O(n) time. For each element, calculate its contribution to all subarrays where it's the minimum using prefix sums of prefix sums to efficiently compute range sums. Complexity: O(n) time, O(n) space. TutorialsPoint - Sum of Total Strength of Wizards | Monotonic Stack with Prefix Sums
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen