Problem 2859

Abstract / Summary

Add the values of the array whose indices have exactly k set bits in their binary representation.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2859.py

class Solution:
    def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
        result = 0

        # a short solution would iterate over all indices and look at bit_count
        # but let's try some tricks with permutations and generate only relevant indices

        # maximum number of bits
        bits = len(bin(len(nums))) - 2 # skip "0b"
        # [ 0,0,0,...,0,1,1,...,1 ]
        base = [ 0 ] * (bits - k) + [ 1 ] * k

        # unfortunately, there is no parameter for itertools to enforce skipping repeated items
        # therefore a set() must eliminate duplicates
        for x in set(permutations(base)):
            index = sum(value << i for i, value in enumerate(x))
            # a few permutations might be out of range
            if index < len(nums):
                result += nums[index]

        # actually, the short solution would be faster ...
        return result
22 lines | 931 bytes | submitted November 16, 2023 | GitHub   90% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method that returns the sum of elements in nums whose positions (zero-based indices) contain exactly k set bits in their binary representation. Instead of scanning every index, the algorithm constructs all possible bit patterns with k ones, converts each pattern into an integer index, filters those that fall inside the array bounds, and accumulates the corresponding values.

Key Steps

Determine the number of bits needed for the index space

bits = len(bin(len(nums))) - 2   # skip "0b"

The length of the binary representation of len(nums) tells how many bits are required to address any element in the list. Subtracting the prefix length yields the exact bit count.

Create a template containing the required number of set bits

base = [0] * (bits - k) + [1] * k

base is a list of length bits that holds k ones and the remaining positions as zeros. This template represents the canonical pattern from which all index permutations will be derived.

Enumerate all distinct permutations of the template

for x in set(permutations(base)):

itertools.permutations would normally generate every ordering, including duplicates when the template contains repeated values. Wrapping the iterator with set removes those duplicates, ensuring each unique arrangement of zeros and ones is processed exactly once.

Translate a permutation into an integer index

index = sum(value << i for i, value in enumerate(x))

Each position i in the permutation corresponds to a bit weight 1 << i. Summing the shifted values reconstructs the integer whose binary form matches the current permutation.

Verify the index is within the array bounds and add the element

if index < len(nums):
    result += nums[index]

Because some permutations may produce numbers larger than the highest valid index, the conditional guards against out-of-range access. Only indices that satisfy the bound contribute to the final sum.

Return the accumulated result

return result

After all unique permutations have been examined, the method yields the total of the selected elements.

Edge Cases Handled

When k equals zero, base becomes a list of all zeros; the only permutation yields index 0, and the method correctly adds nums[0] if the list is non-empty.

If k exceeds the number of bits required for the array length, the expression bits - k produces a negative repeat count, resulting in an empty zero segment and a base consisting solely of ones. The generated permutations correspond to the maximum possible index values; the range check discards any that exceed len(nums) - 1, leaving the sum unchanged.

An empty nums list leads to bits being 1 (binary of 0 is "0b0"). The constructed base may still be formed, but every computed index fails the < len(nums) test, so result remains 0.

Duplicate permutations caused by repeated zeros or ones are eliminated by the set wrapper, preventing redundant additions and ensuring each distinct index contributes at most once.

Performance Optimizations

The algorithm avoids a naïve full-scan of all indices by generating only those bit patterns that satisfy the exact k-set-bit requirement. This reduces the number of candidate indices from len(nums) to the combinatorial count C(bits, k).

Deduplication via set(permutations(...)) prevents repeated work when the template contains identical elements, which would otherwise cause exponential blow-up in the permutation generator.

Computing the integer index with a generator expression that shifts each bit (value << i) is a low-overhead, bitwise operation that runs in constant time per permutation.

The early range check (if index < len(nums)) stops out-of-range indices from participating in the accumulation, eliminating unnecessary array accesses.

Overall, the combination of combinatorial pruning, duplicate elimination, and bitwise arithmetic yields a solution that focuses work exclusively on indices that can possibly meet the k-set-bit criterion.

written by openai gpt

ELI5 - Simplified Explanation

Think of this code like a treasure hunt through a big toy chest. The toy chest has many slots, and each slot is labeled with a secret number. Some of these labels have special glowing stars hidden inside them. The goal is to open only the slots that have exactly the number of stars you are looking for and gather all the toys inside them into a pile.

First, the code looks at the size of the toy chest to figure out how many stars could possibly be tucked away. It creates a special list that acts like a template. This template has the right amount of stars, which are marked as ones, and gaps, which are marked as zeros.

Next, the code starts mixing up the template in every way possible. It treats these different arrangements like a secret code to find the specific slots in the chest. Because some of these codes might point to a spot that does not exist in the chest, the code carefully checks each one before looking inside. If the code points to a real spot, it grabs the toy from that slot and adds it to the big pile. Once every possible combination is checked, the heap of toys is gathered together and ready to play with.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 3 | μ = 3.81 | σ = 1.64

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java Python C++ TS
WalkCCC Java Python C++
leetcode.ca Java Python Go C++ TS
Progiez Java Python C++
github chandansgowda Python
charles-wangkai Java
fsq JS
JoshCrozier JS
muhammadfarhankt Go
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
chandansgowda Python
charles-wangkai Java
fsq JavaScript
JoshCrozier JavaScript
muhammadfarhankt Go
varunu28 Java
21 links | 10 authors | 6 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

3 easy 1 medium
5 solutions   November 16, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality