Find the Sum of Subsequence Powers - Problem
Find the Sum of Subsequence Powers

You're given an integer array nums of length n and a positive integer k. Your task is to find all possible subsequences of length k and calculate their "power" values.

The power of a subsequence is defined as the minimum absolute difference between any two elements in that subsequence. For example, if we have a subsequence [1, 5, 3], the power would be min(|1-5|, |1-3|, |5-3|) = min(4, 2, 2) = 2.

Goal: Return the sum of powers of all subsequences that have exactly k elements. Since the answer can be very large, return it modulo 10^9 + 7.

Note: A subsequence maintains the relative order of elements from the original array but doesn't need to be contiguous.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 2, 3, 4], k = 3
โ€บ Output: 4
๐Ÿ’ก Note: All 3-element subsequences: [1,2,3] (power=1), [1,2,4] (power=1), [1,3,4] (power=1), [2,3,4] (power=1). Sum = 1+1+1+1 = 4
example_2.py โ€” Different Powers
$ Input: nums = [2, 2], k = 2
โ€บ Output: 0
๐Ÿ’ก Note: Only one 2-element subsequence: [2,2]. The power is |2-2| = 0. Sum = 0
example_3.py โ€” Single Element
$ Input: nums = [4, 3, -1], k = 1
โ€บ Output: 0
๐Ÿ’ก Note: Single element subsequences have no pairs to compare, so power is undefined (we return 0 by convention)

Constraints

  • 2 โ‰ค nums.length โ‰ค 50
  • 1 โ‰ค k โ‰ค nums.length
  • -108 โ‰ค nums[i] โ‰ค 108
  • The answer should be returned modulo 109 + 7

Visualization

Tap to expand
Subsequence Power VisualizationExample: nums = [1, 2, 3, 4], k = 3Step 1: All possible 3-element subsequences123โ†’ [1,2,3]124โ†’ [1,2,4]Step 2: Calculate power for each subsequence[1,2,3]: differences = |1-2|=1, |1-3|=2, |2-3|=1 โ†’ min = 1[1,2,4]: differences = |1-2|=1, |1-4|=3, |2-4|=2 โ†’ min = 1[1,3,4]: differences = |1-3|=2, |1-4|=3, |3-4|=1 โ†’ min = 1[2,3,4]: differences = |2-3|=1, |2-4|=2, |3-4|=1 โ†’ min = 1Step 3: Sum all powersTotal = 1 + 1 + 1 + 1 = 4Each subsequence contributes its minimum absolute difference to the final sum๐ŸŽฏ Key Insight: Sort first, then use DP to avoid generating all combinations!
Understanding the Visualization
1
Identify Subsequences
Find all possible subsequences of length k
2
Calculate Powers
For each subsequence, find minimum absolute difference between any two elements
3
Sum All Powers
Add up all the power values to get the final result
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating all possible subsequences (exponential time), sort the array first and use dynamic programming to count subsequences with specific minimum differences, dramatically reducing time complexity.
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 25
26.4K Views
Medium Frequency
~35 min Avg. Time
856 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