Sum of Values at Indices With K Set Bits - Problem
You are given a 0-indexed integer array nums and an integer k.
Return an integer that denotes the sum of elements in nums whose corresponding indices have exactly k set bits in their binary representation.
The set bits in an integer are the 1's present when it is written in binary.
For example: The binary representation of 21 is 10101, which has 3 set bits.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [5,10,1,5,2], k = 1
›
Output:
13
💡 Note:
Check indices: i=0 has 0 set bits, i=1 has 1 set bit (nums[1]=10), i=2 has 1 set bit (nums[2]=1), i=3 has 2 set bits, i=4 has 1 set bit (nums[4]=2). Sum = 10+1+2 = 13.
Example 2 — All Zero Bits
$
Input:
nums = [4,3,2,1], k = 0
›
Output:
4
💡 Note:
Only index 0 has 0 set bits (binary: 0), so we sum only nums[0] = 4.
Example 3 — No Matches
$
Input:
nums = [1,2,3], k = 3
›
Output:
0
💡 Note:
No index from 0-2 has 3 set bits (max is 2 bits for index 3), so sum is 0.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ k ≤ 10
- 0 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums=[5,10,1,5,2] and k=1
2
Process
Check each index binary representation for k set bits
3
Output
Sum values at matching indices: 13
Key Takeaway
🎯 Key Insight: Focus on index bit patterns, not array values - efficient bit counting is the optimization key
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code