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:

  • seq has a size of m
  • 0 <= seq[i] < nums.length
  • The binary representation of 2^seq[0] + 2^seq[1] + ... + 2^seq[m-1] has k set 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
Magical Sequences: nums=[2,3,1], m=2, k=2Input Array231idx 0idx 1idx 2Sequence [0,1]2^0 + 2^1 = 1 + 2 = 3Binary: 11 (2 set bits ✓)Product: 2 × 3 = 6Sequence [1,2]2^1 + 2^2 = 2 + 4 = 6Binary: 110 (2 set bits ✓)Product: 3 × 1 = 3Final Sum: 6 + 3 = 9Only sequences of length m=2 with exactly k=2 set bits
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
Asked in
Google 25 Microsoft 18 Meta 15 Amazon 12
12.0K Views
Medium Frequency
~35 min Avg. Time
450 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