HardNo. 0891

Sum of Subsequence Widths — LeetCode 891 Python Solution

Pattern
Sorting
Topics
Array, Math, Sorting
Reading time
2 min

The problem

The width of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums.

Example

Input
nums = [2,1,3]
Output
6
Explanation
The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].

Python solution

PythonSolution
class Solution:
    def sumSubseqWidths(self, nums: List[int]) -> int:
        mod = 10**9 + 7
        nums.sort()
        ans, p = 0, 1
        for i, v in enumerate(nums):
            ans = (ans + (v - nums[-i - 1]) * p) % mod
            p = (p << 1) % mod
        return ans

Complexity

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 891. Sum of Subsequence Widths is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 891. Sum of Subsequence Widths?

LeetCode 891. Sum of Subsequence Widths is rated Hard on LeetCode.

What topics does LeetCode 891. Sum of Subsequence Widths cover?

LeetCode 891. Sum of Subsequence Widths is tagged Array, Math 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.

Free to download. Check it runs on your machine, then pick a plan.