Power of Heroes - Problem

You are given a 0-indexed integer array nums representing the strength of some heroes. The power of a group of heroes is defined as follows:

Let i₀, i₁, ... ,iₖ be the indices of the heroes in a group. Then, the power of this group is max(nums[i₀], nums[i₁], ... ,nums[iₖ])² × min(nums[i₀], nums[i₁], ... ,nums[iₖ]).

Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,4]
Output: 141
💡 Note: All possible groups: [2]→8, [1]→1, [4]→64, [2,1]→4, [2,4]→32, [1,4]→16, [2,1,4]→16. Sum = 8+1+64+4+32+16+16 = 141
Example 2 — Minimum Size
$ Input: nums = [1]
Output: 1
💡 Note: Only one group [1] with power = 1² × 1 = 1
Example 3 — Equal Elements
$ Input: nums = [3,3]
Output: 81
💡 Note: Groups: [3] (first) → 27, [3] (second) → 27, [3,3] → 27. Sum = 27+27+27 = 81

Constraints

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

Visualization

Tap to expand
Power of Heroes INPUT Array: nums 2 i=0 1 i=1 4 i=2 Sorted: [1, 2, 4] 1 2 4 All groups power formula: max(group)^2 * min(group) Groups: {1},{2},{4},{1,2}, {1,4},{2,4},{1,2,4} 7 non-empty subsets MOD = 10^9 + 7 ALGORITHM STEPS 1 Sort Array Ascending order for contribution counting 2 Track Prefix Sum sum = sum*2 + nums[i] for min contributions 3 Calculate Power For each max: nums[i]^2 times prefix sum 4 Sum All Powers ans += power (mod 10^9+7) Iteration Details i=0: sum=1, pow=1*1=1 i=1: sum=1*2+2=4 pow=4*4=16 i=2: sum=4*2+4=12 pow=16*12=192 Total: 1+16+192=209? --> FINAL RESULT Answer 141 Power Breakdown {1}: 1^2*1 = 1 {2}: 2^2*2 = 8 {4}: 4^2*4 = 64 {1,2}: 2^2*1 = 4 {1,4}: 4^2*1 = 16 {2,4}: 4^2*2 = 32 {1,2,4}: 4^2*1 = 16 Sum: 1+8+64+4+16+32+16 = 141 OK Key Insight: Sort array first. For each element as max, use prefix sum to count all min contributions. When sorted, nums[i] is max for groups with elements from indices 0 to i. The prefix sum doubles at each step (each prior element can be included or not). Time: O(n log n), Space: O(1) TutorialsPoint - Power of Heroes | Prefix Sum with Contribution Counting
Asked in
Google 15 Amazon 12 Meta 8
18.0K Views
Medium Frequency
~35 min Avg. Time
850 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