Find the Sum of Subsequence Powers - Problem

You are given an integer array nums of length n, and a positive integer k.

The power of a subsequence is defined as the minimum absolute difference between any two elements in the subsequence.

Return the sum of powers of all subsequences of nums which have length equal to k.

Since the answer may be large, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4], k = 3
Output: 4
💡 Note: All subsequences of length 3: [1,2,3] (min diff = 1), [1,2,4] (min diff = 1), [1,3,4] (min diff = 1), [2,3,4] (min diff = 1). Sum = 1+1+1+1 = 4
Example 2 — Different Powers
$ Input: nums = [2,2], k = 2
Output: 0
💡 Note: Only one subsequence [2,2] with minimum absolute difference |2-2| = 0. Sum = 0
Example 3 — Single Element
$ Input: nums = [10,7,3], k = 1
Output: 0
💡 Note: When k=1, subsequences have only one element, so no pairs exist to calculate differences. Sum = 0

Constraints

  • 2 ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 50
  • 2 ≤ k ≤ nums.length

Visualization

Tap to expand
Sum of Subsequence Powers: nums=[1,2,3,4], k=31234[1,2,3] → min(|1-2|,|1-3|,|2-3|) = 1[1,2,4] → min(|1-2|,|1-4|,|2-4|) = 1[1,3,4] → min(|1-3|,|1-4|,|3-4|) = 1[2,3,4] → min(|2-3|,|2-4|,|3-4|) = 1Sum = 4Power = minimum absolute difference between any two elementsSum all powers of subsequences with length k
Understanding the Visualization
1
Input
Array nums=[1,2,3,4], k=3 (need subsequences of length 3)
2
Generate
Find all subsequences: [1,2,3], [1,2,4], [1,3,4], [2,3,4]
3
Calculate
Power = min absolute difference in each subsequence
4
Sum
Add all powers: 1+1+1+1=4
Key Takeaway
🎯 Key Insight: Sort first, then use DP to count subsequences by their minimum difference
Asked in
Google 15 Facebook 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
234 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