Sum of Subsequence Widths - 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. 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].

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3]
Output: 6
💡 Note: All subsequences: [2]→0, [1]→0, [3]→0, [2,1]→1, [2,3]→1, [1,3]→2, [2,1,3]→2. Sum = 0+0+0+1+1+2+2 = 6
Example 2 — Single Element
$ Input: nums = [5]
Output: 0
💡 Note: Only one subsequence [5] with width = 5-5 = 0
Example 3 — Two Elements
$ Input: nums = [1,4]
Output: 3
💡 Note: Subsequences: [1]→0, [4]→0, [1,4]→3. Sum = 0+0+3 = 3

Constraints

  • 1 ≤ nums.length ≤ 20000
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Sum of Subsequence Widths INPUT nums = [2, 1, 3] 2 1 3 All Subsequences: [1]: width=0 [2]: width=0 [3]: width=0 [1,2]: width=1 [1,3]: width=2 [2,3]: width=1 [1,2,3]: width=2 Width = max - min Total: 0+0+0+1+2+1+2 = 6 ALGORITHM STEPS 1 Sort Array [2,1,3] --> [1,2,3] 2 Count Contributions Each element contributes as max and min 3 Apply Formula nums[i] * (2^i - 2^(n-1-i)) For sorted [1, 2, 3]: i=0: 1*(1-4) = -3 i=1: 2*(2-2) = 0 i=2: 3*(4-1) = 9 Sum: -3+0+9 = 6 4 Return Result Modulo 10^9 + 7 Time: O(n log n) FINAL RESULT Sum of All Widths 6 Contribution Breakdown: Element 1 (smallest): Max in 0, Min in 4 subseq Element 2 (middle): Max in 2, Min in 2 subseq Element 3 (largest): Max in 4, Min in 0 subseq OK Key Insight: After sorting, element at index i appears as MAXIMUM in 2^i subsequences (choosing from i elements on left), and as MINIMUM in 2^(n-1-i) subsequences (choosing from n-1-i elements on right). Total contribution of nums[i] = nums[i] * (2^i - 2^(n-1-i)). This avoids enumerating all 2^n subsequences! TutorialsPoint - Sum of Subsequence Widths | Optimal Solution O(n log n)
Asked in
Google 45 Amazon 35 Microsoft 30
28.0K Views
Medium Frequency
~35 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen