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
5has binary representation101→ 2 set bits - Index
7has binary representation111→ 3 set bits - Index
8has binary representation1000→ 1 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
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
✓ Linear Growth
Space Complexity
O(1)
Only using constant extra space for variables
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 105
- 0 ≤ k ≤ 10
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code