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:
22
💡 Note:
Valid magical sequences: [0,0] (2^0+2^0=2, 1 set bit, but k=2 so invalid), [0,1] (2^0+2^1=3, 2 set bits, product=2*3=6), [0,2] (2^0+2^2=5, 2 set bits, product=2*1=2), [1,0] (2^1+2^0=3, 2 set bits, product=3*2=6), [1,2] (2^1+2^2=6, 2 set bits, product=3*1=3), [2,0] (2^2+2^0=5, 2 set bits, product=1*2=2), [2,1] (2^2+2^1=6, 2 set bits, product=1*3=3). Sum = 6+2+6+3+2+3 = 22.
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:
5
💡 Note:
Possible sequences of length 2: [0,0] (2^0+2^0=2, 1 set bit, product=1*1=1), [0,1] (2^0+2^1=3, 2 set bits), [1,0] (2^1+2^0=3, 2 set bits), [1,1] (2^1+2^1=4, 1 set bit, product=2*2=4). Valid sequences with k=1 set bits: [0,0] and [1,1]. Sum = 1+4 = 5.
Constraints
- 1 ≤ nums.length ≤ 20
- 1 ≤ nums[i] ≤ 109
- 1 ≤ m ≤ nums.length
- 1 ≤ k ≤ m
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code