Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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.
21 is 10101, which has 3 set bits.Example 1:
Input: nums = [5,10,1,5,2], k = 1 Output: 13 Explanation: The binary representation of the indices are: 0 = 0002 1 = 0012 2 = 0102 3 = 0112 4 = 1002 Indices 1, 2, and 4 have k = 1 set bits in their binary representation. Hence, the answer is nums[1] + nums[2] + nums[4] = 13.
Example 2:
Input: nums = [4,3,2,1], k = 2 Output: 1 Explanation: The binary representation of the indices are: 0 = 002 1 = 012 2 = 102 3 = 112 Only index 3 has k = 2 set bits in its binary representation. Hence, the answer is nums[3] = 1.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 1050 <= k <= 10Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Bit Manipulation
[5,10,1,5,2] 1
[4,3,2,1] 2
counting-bits)find-the-k-or-of-an-array)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2859: Sum of Values at Indices With K Set Bits
class Solution {
public int sumIndicesWithKSetBits(List<Integer> nums, int k) {
int ans = 0;
for (int i = 0; i < nums.size(); i++) {
if (Integer.bitCount(i) == k) {
ans += nums.get(i);
}
}
return ans;
}
}
// Accepted solution for LeetCode #2859: Sum of Values at Indices With K Set Bits
func sumIndicesWithKSetBits(nums []int, k int) (ans int) {
for i, x := range nums {
if bits.OnesCount(uint(i)) == k {
ans += x
}
}
return
}
# Accepted solution for LeetCode #2859: Sum of Values at Indices With K Set Bits
class Solution:
def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
return sum(x for i, x in enumerate(nums) if i.bit_count() == k)
// Accepted solution for LeetCode #2859: Sum of Values at Indices With K Set Bits
/**
* [2859] Sum of Values at Indices With K Set Bits
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn sum_indices_with_k_set_bits(nums: Vec<i32>, k: i32) -> i32 {
let k = k as usize;
let mut result = 0;
for i in 0..nums.len() {
if Solution::num_to_binary(i) == k {
result += nums[i];
}
}
result
}
fn num_to_binary(num: usize) -> usize {
let mut bits = Vec::new();
let mut num = num;
while num != 0 {
bits.push(num % 2);
num = num / 2;
}
bits.iter().filter(|x| **x == 1).count()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2859() {
assert_eq!(
Solution::sum_indices_with_k_set_bits(vec![5, 10, 1, 5, 2], 1),
13
);
assert_eq!(
Solution::sum_indices_with_k_set_bits(vec![4, 3, 2, 1], 2),
1
);
assert_eq!(Solution::sum_indices_with_k_set_bits(vec![1], 0), 1);
assert_eq!(
Solution::sum_indices_with_k_set_bits(vec![1, 1, 3, 1, 6], 2),
1
);
}
}
// Accepted solution for LeetCode #2859: Sum of Values at Indices With K Set Bits
function sumIndicesWithKSetBits(nums: number[], k: number): number {
let ans = 0;
for (let i = 0; i < nums.length; ++i) {
if (bitCount(i) === k) {
ans += nums[i];
}
}
return ans;
}
function bitCount(n: number): number {
let count = 0;
while (n) {
n &= n - 1;
count++;
}
return count;
}
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.