Power of Heroes — LeetCode 2681 Python Solution

HardArrayMathDynamic ProgrammingPrefix SumSorting
Problem
#2681
Pattern
Prefix Sum
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview