Leetcode #2681: Power of Heroes
In this guide, we solve Leetcode #2681 Power of Heroes in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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 i0, i1, ...
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Dynamic Programming, Prefix Sum, Sorting
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: nums = [2,1,4]
Output: 141
Explanation:
1st group: [2] has power = 22 * 2 = 8.
2nd group: [1] has power = 12 * 1 = 1.
3rd group: [4] has power = 42 * 4 = 64.
4th group: [2,1] has power = 22 * 1 = 4.
5th group: [2,4] has power = 42 * 2 = 32.
6th group: [1,4] has power = 42 * 1 = 16.
7th group: [2,1,4] has power = 42 * 1 = 16.
The sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141.
Python Solution
class Solution:
def sumOfPower(self, nums: List[int]) -> int:
mod = 10**9 + 7
nums.sort()
ans = 0
p = 0
for x in nums[::-1]:
ans = (ans + (x * x % mod) * x) % mod
ans = (ans + x * p) % mod
p = (p * 2 + x * x) % mod
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.