Start learning free

LESSON 305 OF 314 · BIT MANIPULATION

Counting Bits in C#: O(n) with a Shift and a Lookup

Practice O(n) Read the full explanation

You get a whole number n.

Return an array bits with n + 1 numbers. For each i, bits[i] is how many 1s the number i has in binary.

 

Example 1:

Input: n = 4
Output: [0,1,1,2,1]
Explanation: Each number in binary:
0 is 0, with no 1s.
1 is 1, with one 1.
2 is 10, with one 1.
3 is 11, with two 1s.
4 is 100, with one 1.

Example 2:

Input: n = 8
Output: [0,1,1,2,1,2,2,3,1]
Explanation: 7 is 111 in binary, so it has three 1s.
8 is 1000, so it has one 1.

Example 3:

Input: n = 0
Output: [0]
Explanation: The only number is 0, and it has no 1s.

 

Constraints:

  • n is from 0 to 100,000.
Note:

Your algorithm should run in O(n) time, a constant amount of work per number, and use O(1) extra space besides the array it returns.



Shifting a number one place to the right drops its last bit: 13 is 1101, and 13 shifted right is 110, which is 6. So 13 has the 1 bits of 6, plus its own last bit.

Fill the answer from 0 up to n. When you reach i, the count of i shifted right by one is already in the array, because that number is smaller than i. Add the last bit of i, which is i AND 1: 1 when i is odd, 0 when it is even.

Each number from 1 to n takes one step: O(n) time.
Apart from the array we return, we keep only the loop variable, so the extra space is O(1).
STEP 1 OF 4
    Ctrl + Enter to check

    C# · BIT MANIPULATION

    Counting Bits in C#, explained

    Problem overview

    The method CountBits receives an int n and returns an int[] of n + 1 numbers. Entry bits[i] is the number of 1 bits in the binary form of i, for every i from 0 to n.

    For n = 5 the numbers 0 to 5 are 0, 1, 10, 11, 100, 101 in binary, so the answer is [0,1,1,2,1,2]. For n = 0 the only number is 0, which has no 1 bits, so the answer is [0].

    Approach: reuse a smaller answer

    You could count the bits of every number on its own, which takes up to about 17 steps per number for n up to 100,000. The lesson does better by noticing that the numbers share work.

    Shifting a number right by one place drops its last bit. 13 is 1101, and 13 shifted right is 110, which is 6. So 13 has the 1 bits of 6, plus its own last bit. That last bit is i & 1: 1 for an odd number and 0 for an even one.

    In a formula, bits[i] = bits[i >> 1] + (i & 1). Since i >> 1 is smaller than i, its count is already in the array when you fill the array from 1 upward. Every number costs one step, so the whole job is O(n).

    Step by step

    1. Create bits as new int[n + 1]. The array holds n + 1 numbers because 0 is included. C# fills a new int array with zeros, and bits[0] is 0 anyway, as 0 has no 1 bits.
    2. Loop i from 1 up to n inclusive (i <= n). Counting upward is essential: each number reads the entry of a smaller one, which must already be filled.
    3. Set bits[i] = bits[i >> 1] + (i & 1). Keep the parentheses around i & 1: in C#, + binds tighter than &, so without them the expression would add first and AND afterwards.
    4. Return bits.

    Here is the array for n = 13:

    [0,1,1,2,1,2,2,3,1,2,2,3,2,3]
    

    Entry 13 is bits[6] + (13 & 1), which is 2 + 1 = 3, matching 1101.

    The solution in C#

    class Solution {
        public int[] CountBits(int n) {
            int[] bits = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                bits[i] = bits[i >> 1] + (i & 1);
            }
            return bits;
        }
    }
    

    Details worth knowing:

    • Array size and last index. An array of length n + 1 has valid indices 0 to n, so bits[n] is valid. Reading or writing beyond it throws IndexOutOfRangeException.
    • >> on an int is an arithmetic shift, which keeps the sign for negative numbers. Here i is never negative, so it simply halves i and rounds down: i >> 1 equals i / 2 for non-negative values.
    • i & 1 is an int. It is 0 or 1, so it adds to the other count directly with no cast.

    Complexity

    Time: O(n). The loop does one lookup, one shift, one AND and one addition per number. Space: O(1) besides the returned array, which has to exist anyway: only the loop variable i is extra.

    Edge cases and common mistakes

    • n = 0. The loop doesn't run and the result is [0], an array of one element.
    • Size n instead of n + 1. The last write, bits[n], would throw an IndexOutOfRangeException.
    • Stopping at i < n. The last entry would stay 0 and be wrong.
    • Missing parentheses. bits[i >> 1] + i & 1 adds first, then ANDs the sum with 1, giving only 0 or 1 for every entry.
    • Looping downward. The entry for i >> 1 would still be 0 when it's needed.

    Testing

    • n = 2 gives [0,1,1].
    • n = 5 gives [0,1,1,2,1,2].
    • n = 0 gives [0].
    • n = 13 gives [0,1,1,2,1,2,2,3,1,2,2,3,2,3].
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free