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 of Values at Indices With K Set Bits INPUT Array nums: 5 i=0 10 i=1 1 i=2 5 i=3 2 i=4 Index Binary Representations: 0 = 000 (0 bits) 1 = 001 (1 bit) 2 = 010 (1 bit) 3 = 011 (2 bits) 4 = 100 (1 bit) k = 1 (target set bits) ALGORITHM STEPS 1 Initialize sum = 0 Result accumulator 2 Loop through indices for i = 0 to n-1 3 Count set bits popcount(i) == k? 4 Add to sum sum += nums[i] Processing: i=0: bits=0, skip i=1: bits=1, add 10 i=2: bits=1, add 1 i=3: bits=2, skip i=4: bits=1, add 2 FINAL RESULT Selected Elements (k=1 set bits): 10 i=1 1 i=2 2 i=4 Calculation: 10 + 1 + 2 = 13 Output: 13 OK - Sum computed 3 indices matched k=1 Key Insight: Use built-in popcount function to efficiently count set bits (1s) in binary representation. Time Complexity: O(n) where n is array length. Each popcount is O(1) with hardware support. TutorialsPoint - Sum of Values at Indices With K Set Bits | Built-in Bit Count Approach
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