Sum of Subsequence Widths - Problem

Imagine you have an array of integers, and you want to explore all possible subsequences (sequences formed by removing some or no elements while maintaining order). Each subsequence has a width - the difference between its maximum and minimum elements.

Your task is to find the sum of widths of all non-empty subsequences.

Example: For array [2, 1, 3], the subsequences are:

  • [2] → width = 2 - 2 = 0
  • [1] → width = 1 - 1 = 0
  • [3] → width = 3 - 3 = 0
  • [2, 1] → width = 2 - 1 = 1
  • [2, 3] → width = 3 - 2 = 1
  • [1, 3] → width = 3 - 1 = 2
  • [2, 1, 3] → width = 3 - 1 = 2

Total sum = 0 + 0 + 0 + 1 + 1 + 2 + 2 = 6

Since the answer can be very large, return it modulo 109 + 7.

Input & Output

example_1.py — Basic Case
$ Input: [2, 1, 3]
Output: 6
💡 Note: Subsequences: [2]→0, [1]→0, [3]→0, [2,1]→1, [2,3]→1, [1,3]→2, [2,1,3]→2. Sum = 6
example_2.py — Single Element
$ Input: [1]
Output: 0
💡 Note: Only one subsequence [1] with width = 1-1 = 0
example_3.py — Two Elements
$ Input: [5, 3]
Output: 4
💡 Note: Subsequences: [5]→0, [3]→0, [5,3]→2. Sum = 4 (after modulo, but result is small)

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • -105 ≤ nums[i] ≤ 105
  • Return result modulo 109 + 7

Visualization

Tap to expand
Sum of Subsequence Widths: Mathematical ApproachStep 1: Sort ArrayOriginal: [2, 1, 3]Sorted: [1, 2, 3]Step 2: Calculate Contributions1Position 0Max in: 2^0=1Min in: 2^2=41×(1-4)=-32Position 1Max in: 2^1=2Min in: 2^1=22×(2-2)=03Position 2Max in: 2^2=4Min in: 2^0=13×(4-1)=9Total: -3 + 0 + 9 = 6💡 Key Insight:After sorting, element at position i contributes: value × (2^i - 2^(n-1-i))
Understanding the Visualization
1
Sort Musicians by Height
Arrange in ascending order to establish clear max/min relationships
2
Calculate Individual Contributions
Each person contributes positively when tallest in group, negatively when shortest
3
Sum All Contributions
Add up positive and negative contributions to get total visual impact
Key Takeaway
🎯 Key Insight: Mathematical optimization transforms an exponential brute force problem into O(n log n) by calculating each element's net contribution across all subsequences.
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 22
42.0K Views
Medium-High Frequency
~18 min Avg. Time
1.9K 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