Sum Of Subsequence Widths Problem
Description
LeetCode Problem 891.
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. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [2,1,3]
Output: 6
Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.
Example 2:
Input: nums = [2]
Output: 0
Constraints:
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^5
Solution
Approach: Sort and Count How Often Each Number Is the Max or the Min
There are 2n − 1 subsequences, far too many to list. But the sum of widths is
sum over subsequences of (max − min) = (sum of all maxima) − (sum of all minima),
so it is enough to know, for each number, how many subsequences have it as their maximum, and how many as their minimum.
The width only depends on which values are chosen, not their order, so we can sort nums first. After sorting, look at nums[i]:
- It is the maximum of a subsequence when every other chosen element comes from the
ielements before it. Each of those can be in or out, so that is 2i subsequences. - It is the minimum when the others come from the
n − 1 − ielements after it: 2n−1−i subsequences.
So nums[i] adds nums[i] · (2^i − 2^(n−1−i)) to the answer. Precompute the powers of 2 modulo 109 + 7 and sum these terms.
Equal values do not need special care. Ties are broken by position in the sorted array, so every subsequence still has exactly one counted maximum and one counted minimum, and the widths come out right.
The detail people get wrong is the modular subtraction: 2^i − 2^(n−1−i) is often negative after taking the modulus, so add 109 + 7 before the final % (Python's % already returns a non-negative value). Also multiply in 64-bit, since nums[i] times a residue reaches about 1014.
Example 1: sorted [1, 2, 3] gives 1·(1 − 4) + 2·(2 − 2) + 3·(4 − 1) = −3 + 0 + 9 = 6.
Complexity: O(n log n) time for the sort and O(n) space for the powers of 2, where n is the length of nums.
class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
MOD = 10**9 + 7
nums.sort()
n = len(nums)
power = [1] * n # power[i] = 2^i mod MOD
for i in range(1, n):
power[i] = power[i - 1] * 2 % MOD
total = 0
for i, x in enumerate(nums):
# x is the maximum of 2^i subsequences and the minimum of 2^(n-1-i).
total = (total + x * (power[i] - power[n - 1 - i])) % MOD
return total