Counting Bits
Every problem here answers how many bits are set, not which ones. That single primitive - the popcount - is the whole page: x.bit_count() in Python 3.10+, or Kernighan's n &= n - 1 loop, which spins once per set bit instead of once per bit width.
Once you have the count, problems differ only in what they do with it: return it, sort by it, use its parity, or search for the numbers that produce a given one.
Popcount
Count the 1s in a single number, or in every number up to n. The DP recurrence dp[i] = dp[i >> 1] + (i & 1) builds the whole table in one pass by reusing the answer for i without its lowest bit.
191. Number of 1 Bits
The number of set bits is the Hamming weight. Test the least significant bit with n & 1, add it to the count, then right-shift n to expose the next bit. The loop ends once n becomes 0. This visits every bit position, set or not.
- Time
- O(1)
- Bounded by the fixed 32-bit width of
n. - Space
- O(1)
- Only the counter is stored.
338. Counting Bits
Brian Kernighan's trick clears the lowest set bit: i & (i - 1). That gives a recurrence, popcount(i) = 1 + popcount(i & (i - 1)), with base case popcount(0) = 0. Write it as a bare top-down recursion and let @lru_cache memoize every call. The one thing to watch: the answer is the whole array of counts for 0..n, not just popcount(n), so the recursion is called once per index and collected into a list.
- Time
- O(n)
@lru_cachemeans each of thendistinct subproblems is solved once; every other call is a cache hit.- Space
- O(n)
- The cache holds up to
nentries, plus then + 1-element result list.
2595. Number of Even and Odd Bits
Walk the bits from least significant upward, tracking the position pos. Whenever the LSB is set, increment even if pos is even and odd if pos is odd. Shift right to advance and stop once n is 0.
- Time
- O(log N)
- One iteration per bit of
n. - Space
- O(1)
- Two counters and a position index.
1356. Sort Integers by The Number of 1 Bits
Sort with a composite key: first by number of set bits, then by the value itself to break ties. Python's sorted is stable, so the (hammingWeight(i), i) tuple orders elements with the same bit count by their natural value.
- Time
- O(N log N)
sortedmakesO(N log N)comparisons, and each of theNelements computes its(hammingWeight(i), i)key once.- Space
- O(sort + N)
sortedreturns a new list ofNelements, on top of the sort's own working memory.- Sorting algorithms are typically
O(log n)space (in-place, recursion stack only), but Python'ssorted()is Timsort, which allocates up toO(n)auxiliary space in the worst case - that's whatsortstands for here.
2859. Sum of Values at Indices With K Set Bits
Scan each element with its index. The condition is about the index, not the value: count the set bits of i, and if that equals k, add nums[i] to the running total.
- Time
- O(N log N)
- Each of the N indices needs a Hamming-weight count over its bits.
- Space
- O(1)
- Only the running total is stored.
Bit Length
A close cousin of popcount: instead of counting how many bits are set, count how many bits it takes to represent the number at all - the position of the highest set bit, plus one. The same shift loop applies, just without checking the bit's value.
Find Bit Length of a Number
The bit length is the position of the highest set bit, plus one. Right-shifting n one bit at a time discards the lowest bit each time; counting shifts until n becomes 0 counts exactly that many bit positions - equivalent to Python's built-in n.bit_length().
- Time
- O(log n)
- The
while nloop shiftsnright by one bit each iteration until it reaches0, once per bit ofn:O(log n). - Space
- O(1)
- Only the counter is maintained.
Hamming Distance
Counting the positions where two numbers differ is popcount with one extra step: XOR them first, so every differing position becomes a 1, then count. The same shape covers "how many flips to turn a into b" and its multi-operand variants.
461. Hamming Distance
The Hamming distance is the number of bit positions where x and y differ. XOR outputs 1 exactly where two bits disagree, so x ^ y marks every differing position. Counting the set bits of that XOR gives the distance directly.
- Time
- O(1)
- Bounded by the fixed bit width of the integers.
- Space
- O(1)
- Only the XOR and counter are stored.
2220. Minimum Bit Flips to Convert Number
Converting start to goal one bit at a time costs one flip per differing bit - which is exactly the Hamming distance. XOR the two numbers to mark every position that differs, then count the set bits of the result.
- Time
- O(1)
- Bounded by the fixed bit width of the integers.
- Space
- O(1)
- Only the XOR and counter are stored.
1318. Minimum Flips to Make a OR b Equal to c
We need a | b == c. Wherever (a | b) ^ c is 1 the bits disagree and must be flipped, so counting those set bits gives the base answer. One exception: when c's bit is 0 but both a and b have a 1 there, a single flip is not enough - both must be cleared, costing an extra flip. Those positions are exactly where a & b is set and the mismatch is set, so add their count too.
- Time
- O(2 log N)
- Two separate
hammingWeightcalls, each a Kernighan's-algorithm loop bounded by the bit width -log N + log Ncollapses to2 log N. - Space
- O(1)
- No additional space beyond the
bitscounter inside eachhammingWeightcall.
2997. Minimum Number of Operations to Make Array XOR Equal to K
Each operation flips a single bit of one element, which flips that bit in the overall XOR. So the task reduces to the Hamming distance: fold the array into a running XOR, then count the set bits of xor ^ k - that is how many bit positions must change to turn the current XOR into k.
- Time
- O(n)
n = len(nums). Thefor i in numsloop folds every element intoxoronce -O(n)- thenhammingWeightstrips one bit at a time from a fixed-width integer, a constant number of iterations independent ofn.- Space
- O(1)
- Only the
xorandbitsaccumulators are stored; nothing scales withn.
Enumerate by Popcount
Here the popcount is a filter or a key, not the answer. Walk a small search space and keep only the candidates with the right number of set bits, or exploit the parity of the popcount to answer in O(1) what a simulation would take O(2^n) to reach.
401. Binary Watch
401Binary Watch
Only 720 valid times exist, so enumerate them all instead of choosing which LEDs to light. Precompute the Hamming weight of every value 0..59 with num & (num - 1), then bucket each hour:minute pair under ones_map[hour] + ones_map[minute]. The answer for any turnedOn is a dictionary lookup.
- Time
- O(1)
- 60 popcounts plus a fixed 12 x 60 sweep - the work never depends on the input.
- Space
- O(1)
- The popcount table and the bucket map hold a fixed 60 + 720 entries.
3304. Find the K-th Character in String Game I
Play the game literally: word starts as "ab". Each round, a new block is produced by shifting every character of the block just added one letter forward (chr(ord(i)+1)), and that new block is appended to both char (the running "delta" block) and word. Repeat until word is at least k characters long, then read off index k - 1.
- Time
- O(k)
wordroughly doubles in length each round, so the total work across all rounds sums to O(k).- Space
- O(k)
wordandchargrow to O(k) characters before the loop stops.