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
Sum Values at Indices With K=1 Set Bits510152i=0i=1i=2i=3i=40: 0 bits1: 1 bit ✓10: 1 bit ✓11: 2 bits100: 1 bit ✓Sum values where index has exactly k=1 set bitsResult: 10 + 1 + 2 = 13
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
Asked in
Amazon 15 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
345 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