Power of Heroes — LeetCode 2681 Python Solution
HardArrayMathDynamic ProgrammingPrefix SumSorting
- Problem
- #2681
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The 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 i0, i1, ...
Example
- Input
- nums = [2,1,4]
- Output
- 141
- Explanation
- 1st group: [2] has power = 22 * 2 = 8.
Python solution
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2681. Power of Heroes is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2681. Power of Heroes?
- LeetCode 2681. Power of Heroes is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2681. Power of Heroes?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2681. Power of Heroes?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2681. Power of Heroes cover?
- LeetCode 2681. Power of Heroes is tagged Array, Math, Dynamic Programming, Prefix Sum and Sorting on LeetCode.