Sum of Values at Indices With K Set Bits - Problem

Given a 0-indexed integer array nums and an integer k, you need to find the sum of all elements in the array whose array indices have exactly k set bits in their binary representation.

A set bit is a bit with value 1 in the binary representation of a number. For example:

  • Index 5 has binary representation 1012 set bits
  • Index 7 has binary representation 1113 set bits
  • Index 8 has binary representation 10001 set bit

Goal: Return the sum of nums[i] for all indices i where the binary representation of i contains exactly k ones.

Input & Output

example_1.py — Basic Case
$ Input: nums = [5,10,1,5,2], k = 1
Output: 13
💡 Note: Indices with exactly 1 set bit: 1 (binary: 1), 2 (binary: 10), 4 (binary: 100). Sum: nums[1] + nums[2] + nums[4] = 10 + 1 + 2 = 13
example_2.py — Multiple Set Bits
$ Input: nums = [4,3,2,1], k = 2
Output: 1
💡 Note: Only index 3 has exactly 2 set bits (binary: 11). Sum: nums[3] = 1
example_3.py — Edge Case k=0
$ Input: nums = [1,2,3], k = 0
Output: 1
💡 Note: Only index 0 has exactly 0 set bits (binary: 0). Sum: nums[0] = 1

Visualization

Tap to expand
Array Index Binary Analysis (k=2)nums510152Index Analysis:012340110111000 bits1 bit1 bit2 bits1 bitResult for k=2:Only index 3 has exactly 2 set bitsBinary: 11₂ → count=2Sum = nums[3] = 5
Understanding the Visualization
1
Index to Binary
Convert array index to binary representation
2
Count Set Bits
Use efficient bit manipulation to count 1's
3
Compare and Sum
If count equals k, add array value to result
Key Takeaway
🎯 Key Insight: Use efficient bit manipulation functions to count set bits instead of string conversion for optimal O(n) performance.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through array, bit counting is O(1) with built-in functions

n
2n
Linear Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 105
  • 0 ≤ k ≤ 10
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
28.5K Views
Medium Frequency
~8 min Avg. Time
890 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