The Counting Bits interview question asks you to return an array of length where each entry is the number of 1s in the binary representation of the integer (from to ). For example, if , you need to return counts for 0 (00), 1 (01), and 2 (10), which is [0, 1, 1].
Companies like Uber and Nvidia use this Bit Manipulation interview pattern to see if a candidate can optimize a calculation using previously computed values. While you could calculate bits for each number independently in O(n log n), the goal is to solve it in O(n) using Dynamic Programming. It tests your ability to find mathematical relationships between binary numbers.
This problem is solved using Dynamic Programming with Bit Manipulation. There are several relationships you can use:
dp[i] = dp[i - offset] + 1, where offset is the largest power of 2 less than or equal to .dp[i] = dp[i >> 1] + (i & 1).
The LSB approach is the most elegant: the number of bits in is the number of bits in plus 1 if is odd.
dp[0] = 0dp[1]: dp[1 >> 1] + (1 & 1) = dp[0] + 1 = 1.dp[2]: dp[2 >> 1] + (2 & 1) = dp[1] + 0 = 1.dp[3]: dp[3 >> 1] + (3 & 1) = dp[1] + 1 = 2.dp[4]: dp[4 >> 1] + (4 & 1) = dp[2] + 0 = 1.dp[5]: dp[5 >> 1] + (5 & 1) = dp[2] + 1 = 2.
Result: [0, 1, 1, 2, 1, 2].dp array itself is the solution and trying to use extra storage.Master the expression i >> 1 (division by 2) and i & 1 (parity check). These are fundamental tools for almost any binary-related coding problem.