2859. Sum of Values at Indices With K Set Bits
Problem Description
You are given an integer array nums
(0-indexed) and an integer k
.
Your task is to find the sum of all elements in nums
whose indices have exactly k
set bits in their binary representation.
A set bit is a 1
in the binary representation of a number. For example, the number 21
in binary is 10101
, which contains 3 set bits (three 1
s).
The key point is that you need to check the index positions (not the array values themselves) to see if they have exactly k
set bits. If an index i
has exactly k
set bits in its binary form, then you add nums[i]
to your sum.
For instance, if k = 2
:
- Index
3
in binary is11
, which has 2 set bits → includenums[3]
in the sum - Index
5
in binary is101
, which has 2 set bits → includenums[5]
in the sum - Index
4
in binary is100
, which has 1 set bit → do not includenums[4]
The solution uses Python's bit_count()
method to count the number of 1
s in the binary representation of each index, then sums up the corresponding array elements where the count equals k
.
Intuition
The problem asks us to sum elements based on a property of their indices, not the elements themselves. This immediately tells us we need to examine each index individually.
Since we need to check if each index has exactly k
set bits in its binary representation, the natural approach is to iterate through all indices and check this condition. There's no clever trick to avoid checking each index because any index could potentially have exactly k
set bits - there's no pattern we can exploit to skip indices.
The straightforward solution emerges from breaking down what we need to do:
- For each index
i
in the array - Count how many
1
s are in the binary representation ofi
- If that count equals
k
, addnums[i]
to our running sum
This leads directly to a simple iteration approach. We don't need any complex data structures or algorithms - just a linear scan through the array indices.
The Python solution becomes elegant because of the built-in bit_count()
method which directly gives us the number of set bits. Combined with enumerate to get both indices and values simultaneously, and a generator expression with sum, we can write this in a single line. The logic flow is: enumerate gives us (index, value)
pairs → filter those where index.bit_count() == k
→ sum the values that pass the filter.
This is essentially a filtering problem where the filter condition is based on the binary representation of the index position.
Solution Approach
The solution uses a simulation approach - we directly check each index to see if it meets our condition.
The implementation iterates through each index i
from 0
to len(nums) - 1
and checks whether the number of 1
s in the binary representation of i
equals k
. If the condition is met, we add the corresponding element nums[i]
to our answer.
Here's how the algorithm works step by step:
-
Initialize the sum: Start with a sum of
0
(handled implicitly by Python'ssum()
function) -
Iterate through the array with indices: Use
enumerate(nums)
to get both the indexi
and the valuex
at that index simultaneously -
Count set bits for each index: For each index
i
, usei.bit_count()
to count the number of1
s in its binary representation -
Check the condition: Compare the bit count with
k
usingi.bit_count() == k
-
Accumulate qualifying elements: If the condition is true, include the element
x
in the sum
The Python implementation combines all these steps into a single line using a generator expression:
sum(x for i, x in enumerate(nums) if i.bit_count() == k)
This generator expression:
- Produces values
x
(elements fromnums
) - Only when their corresponding index
i
has exactlyk
set bits - The
sum()
function then adds all these qualifying elements together
The time complexity is O(n)
where n
is the length of the array, as we visit each element once. The space complexity is O(1)
since we only use a constant amount of extra space (the generator doesn't create an intermediate list).
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [5, 10, 1, 5, 2]
and k = 1
.
We need to find indices that have exactly 1 set bit in their binary representation, then sum the corresponding elements.
Step 1: Check each index's binary representation
- Index 0: binary =
0
→ has 0 set bits → skipnums[0] = 5
- Index 1: binary =
1
→ has 1 set bit → includenums[1] = 10
- Index 2: binary =
10
→ has 1 set bit → includenums[2] = 1
- Index 3: binary =
11
→ has 2 set bits → skipnums[3] = 5
- Index 4: binary =
100
→ has 1 set bit → includenums[4] = 2
Step 2: Sum the qualifying elements Indices 1, 2, and 4 have exactly 1 set bit, so we sum:
nums[1] + nums[2] + nums[4] = 10 + 1 + 2 = 13
Using the Python solution:
sum(x for i, x in enumerate(nums) if i.bit_count() == k)
The generator expression processes:
(0, 5)
:0.bit_count() = 0 ≠ 1
→ skip(1, 10)
:1.bit_count() = 1 = 1
→ yield 10(2, 1)
:2.bit_count() = 1 = 1
→ yield 1(3, 5)
:3.bit_count() = 2 ≠ 1
→ skip(4, 2)
:4.bit_count() = 1 = 1
→ yield 2
The sum function adds: 10 + 1 + 2 = 13
This demonstrates how the solution efficiently filters elements based on their index's bit count property.
Solution Implementation
1class Solution:
2 def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
3 """
4 Calculate the sum of elements whose indices have exactly k set bits in binary representation.
5
6 Args:
7 nums: List of integers
8 k: Target number of set bits in index binary representation
9
10 Returns:
11 Sum of elements at indices with exactly k set bits
12 """
13 # Initialize sum to accumulate qualifying elements
14 total_sum = 0
15
16 # Iterate through the array with index and value
17 for index, value in enumerate(nums):
18 # Check if the binary representation of index has exactly k set bits
19 # bit_count() returns the number of 1s in binary representation
20 if bin(index).count('1') == k:
21 # Add the value to sum if condition is met
22 total_sum += value
23
24 return total_sum
25```
26
27Note: The original code uses `i.bit_count()` which is available in Python 3.10+. The rewritten version uses `bin(index).count('1')` which works in earlier Python 3 versions as well. If you specifically need Python 3.10+ syntax, here's an alternative:
28
29```python3
30class Solution:
31 def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
32 """
33 Calculate the sum of elements whose indices have exactly k set bits in binary representation.
34
35 Args:
36 nums: List of integers
37 k: Target number of set bits in index binary representation
38
39 Returns:
40 Sum of elements at indices with exactly k set bits
41 """
42 # Use list comprehension to filter and sum elements
43 # where index has exactly k set bits
44 return sum(
45 value # Sum the values
46 for index, value in enumerate(nums) # Iterate with indices
47 if index.bit_count() == k # Filter by bit count condition
48 )
49
1class Solution {
2 /**
3 * Calculates the sum of elements at indices that have exactly k set bits in their binary representation.
4 *
5 * @param nums The list of integers to process
6 * @param k The target number of set bits in the index
7 * @return The sum of elements at qualifying indices
8 */
9 public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
10 int sum = 0;
11
12 // Iterate through all indices of the list
13 for (int index = 0; index < nums.size(); index++) {
14 // Check if the current index has exactly k set bits in its binary representation
15 if (Integer.bitCount(index) == k) {
16 // Add the element at this index to the running sum
17 sum += nums.get(index);
18 }
19 }
20
21 return sum;
22 }
23}
24
1class Solution {
2public:
3 /**
4 * Calculate the sum of elements at indices where the binary representation
5 * has exactly k set bits (1s)
6 * @param nums - input vector of integers
7 * @param k - required number of set bits in the index
8 * @return sum of elements at qualifying indices
9 */
10 int sumIndicesWithKSetBits(vector<int>& nums, int k) {
11 int sum = 0;
12
13 // Iterate through all indices of the array
14 for (int index = 0; index < nums.size(); ++index) {
15 // Check if current index has exactly k set bits in binary representation
16 if (__builtin_popcount(index) == k) {
17 // Add the element at this index to the sum
18 sum += nums[index];
19 }
20 }
21
22 return sum;
23 }
24};
25
1/**
2 * Calculates the sum of elements in nums array where the index has exactly k set bits
3 * @param nums - The input array of numbers
4 * @param k - The target number of set bits in the index
5 * @returns The sum of elements at indices with k set bits
6 */
7function sumIndicesWithKSetBits(nums: number[], k: number): number {
8 let sum: number = 0;
9
10 // Iterate through each index in the array
11 for (let index: number = 0; index < nums.length; index++) {
12 // Check if the current index has exactly k set bits
13 if (bitCount(index) === k) {
14 // Add the element at this index to the sum
15 sum += nums[index];
16 }
17 }
18
19 return sum;
20}
21
22/**
23 * Counts the number of set bits (1s) in the binary representation of a number
24 * Uses Brian Kernighan's algorithm for efficient bit counting
25 * @param n - The number to count set bits in
26 * @returns The count of set bits
27 */
28function bitCount(n: number): number {
29 let count: number = 0;
30
31 // Keep clearing the rightmost set bit until n becomes 0
32 while (n !== 0) {
33 // Clear the rightmost set bit
34 n &= n - 1;
35 // Increment the count for each cleared bit
36 count++;
37 }
38
39 return count;
40}
41
Time and Space Complexity
Time Complexity: O(n × log n)
, where n
is the length of the array nums
.
The algorithm iterates through all indices from 0
to n-1
using enumerate(nums)
, which takes O(n)
time. For each index i
, the bit_count()
method is called to count the number of set bits (1s) in the binary representation of i
. The bit_count()
operation takes O(log i)
time since the number of bits in the binary representation of i
is proportional to log i
. In the worst case, when i = n-1
, this becomes O(log n)
. Therefore, the overall time complexity is O(n) × O(log n) = O(n × log n)
.
Space Complexity: O(1)
.
The algorithm uses a generator expression with sum()
, which processes elements one at a time without storing them all in memory. Only a constant amount of extra space is used for variables like the running sum and the current index/value pair from enumerate()
. No additional data structures that scale with input size are created.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Confusing Index vs Value for Bit Counting
The Pitfall: A very common mistake is counting the set bits in the array values instead of the indices. Many developers instinctively check nums[i].bit_count() == k
instead of i.bit_count() == k
.
Wrong Implementation:
# INCORRECT - This counts bits in the values, not indices!
def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
return sum(x for x in nums if x.bit_count() == k)
Correct Implementation:
# CORRECT - This counts bits in the indices
def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
return sum(x for i, x in enumerate(nums) if i.bit_count() == k)
2. Handling Negative Numbers in the Array
The Pitfall: While the indices are always non-negative, the array values can be negative. Using bit_count()
on negative values would cause an error since negative numbers don't have a bit_count()
method in Python.
Example that would fail if checking values:
nums = [-5, 10, -3, 7] # Contains negative numbers k = 2 # If you mistakenly try nums[i].bit_count(), it will fail for negative values
Solution: Always remember we're checking indices (which are guaranteed to be non-negative), not the values themselves.
3. Python Version Compatibility
The Pitfall: The bit_count()
method was introduced in Python 3.10. Using it in earlier versions will result in an AttributeError.
Version-Safe Alternatives:
# Option 1: Using bin() and count() - works in all Python 3.x
if bin(i).count('1') == k:
total_sum += value
# Option 2: Using bitwise operations - more manual but universal
def count_set_bits(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
if count_set_bits(i) == k:
total_sum += value
4. Edge Case: k = 0
The Pitfall: Forgetting that when k = 0
, only index 0 qualifies (since 0 in binary is just 0
with zero set bits). This means only nums[0]
should be included in the sum.
Test Case to Remember:
nums = [5, 10, 1, 5, 2] k = 0 # Expected output: 5 (only nums[0] is included) # Index 0 binary: 0 (has 0 set bits) ✓ # Index 1 binary: 1 (has 1 set bit) ✗ # Index 2 binary: 10 (has 1 set bit) ✗
5. Empty Array or k Greater Than Possible Set Bits
The Pitfall: Not considering edge cases where the array is empty or k is larger than the maximum possible set bits for any index in the array.
Handling Edge Cases:
def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
# Empty array returns 0
if not nums:
return 0
# If k is impossibly large for the given array size
# (e.g., k=10 but array has only 100 elements, max index 99 = 1100011 has 4 bits)
# The sum will naturally be 0 as no index will match
return sum(x for i, x in enumerate(nums) if i.bit_count() == k)
In a binary min heap, the maximum element can be found in:
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!