Find Sum of Array Product of Magical Sequences - Problem
You are given two integers m and k, and an integer array nums.
A sequence of integers seq is called magical if:
seqhas a size ofm0 <= seq[i] < nums.length- The binary representation of
2^seq[0] + 2^seq[1] + ... + 2^seq[m-1]haskset bits
The array product of this sequence is defined as prod(seq) = (nums[seq[0]] * nums[seq[1]] * ... * nums[seq[m-1]]).
Return the sum of the array products for all valid magical sequences. Since the answer may be large, return it modulo 10^9 + 7.
A set bit refers to a bit in the binary representation of a number that has a value of 1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,3,1], m = 2, k = 2
›
Output:
9
💡 Note:
Valid magical sequences: [0,1] (2^0+2^1=3, 2 set bits, product=2*3=6) and [1,2] (2^1+2^2=6, 2 set bits, product=3*1=3). Sum = 6+3 = 9.
Example 2 — Single Element
$
Input:
nums = [5], m = 1, k = 1
›
Output:
5
💡 Note:
Only sequence [0] is valid: 2^0=1 has 1 set bit, product=5.
Example 3 — No Valid Sequences
$
Input:
nums = [1,2], m = 2, k = 1
›
Output:
0
💡 Note:
No sequence of length 2 can have exactly 1 set bit since we need 2^i + 2^j where i≠j, which always has at least 2 set bits.
Constraints
- 1 ≤ nums.length ≤ 20
- 1 ≤ nums[i] ≤ 109
- 1 ≤ m ≤ nums.length
- 1 ≤ k ≤ m
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums=[2,3,1], m=2, k=2
2
Process
Find sequences where power sum has exactly k set bits
3
Output
Sum of all valid sequence products
Key Takeaway
🎯 Key Insight: Use dynamic programming to efficiently count magical sequences by tracking length and set bit combinations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code