Start learning free

LESSON 305 OF 314 · BIT MANIPULATION

Counting Bits in Rust: O(n) with Dynamic Programming on Shifts

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

    RUST · BIT MANIPULATION

    Counting Bits in Rust, explained

    Problem overview

    The function count_bits receives an integer n and returns a vector of n + 1 numbers. Entry 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 answer is [0].

    Approach: reuse the answer for a smaller number

    Counting the bits of each number separately works, but it costs up to about 17 steps per number for n up to 100,000. The lesson wants a constant amount of work per number, so each answer has to come from one that is already known.

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

    bits[i] = bits[i >> 1] + (i & 1)

    The value i >> 1 is smaller than i for every i of at least 1, so filling the vector from left to right guarantees that its entry is already there. And i & 1 is 1 for odd numbers and 0 for even ones. For n = 13 the loop produces [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3]: the last entry is bits[6] + 1 = 2 + 1 = 3.

    Step by step

    1. Create bits with n + 1 zeros. The size is n as usize + 1, because vector sizes are usize. The entry for 0 is already correct.
    2. Loop i from 1 up to bits.len(). The range 1..bits.len() stops before the length, so the last i is n. Going upward matters: each entry needs the one for i >> 1 to be filled in first.
    3. Apply the formula. Take the stored count for i >> 1 and add the last bit of i.
    4. Return bits as the last expression, without a semicolon.

    The solution in Rust

    impl Solution {
        fn count_bits(n: i32) -> Vec<i32> {
            let mut bits = vec![0i32; n as usize + 1];
            for i in 1..bits.len() {
                bits[i] = bits[i >> 1] + (i & 1) as i32;
            }
            bits
        }
    }
    

    Rust details worth knowing:

    • Types. The loop variable i is a usize, because it indexes the vector, so i >> 1 and i & 1 are usize values too. The counts stored in bits are i32, so the last bit needs as i32 before it can be added. Rust never adds two different integer types silently.
    • Parentheses. (i & 1) as i32 converts the result of the AND. Without the parentheses, i & 1 as i32 would cast only the 1, and the AND of a usize with an i32 would not compile.
    • vec![0i32; n as usize + 1]. The suffix 0i32 fixes the element type, which matches the return type Vec<i32>. The cast n as usize comes before the + 1, because as binds tighter than +.
    • Indexing is checked. Reading bits[i >> 1] is always inside the vector here. An index out of range would panic, never read memory it shouldn't.

    Complexity

    Time: O(n). The loop runs n times, and each pass does a shift, an AND, an addition and a store.

    Space: O(1) extra. Apart from the vector that the function returns, only the loop variable is kept.

    Edge cases and common mistakes

    • n = 0. The vector has one entry, [0], and the range 1..1 is empty, so the loop doesn't run.
    • Off by one on the size. The answer needs n + 1 entries, because 0 is included. A vector of n entries would panic when the loop reaches the last index.
    • Looping the wrong way. Going from n down to 1 would read entries that are still 0.
    • Mixing types. bits[i >> 1] + (i & 1) without as i32 is a compile error, because an i32 and a usize can't be added.
    • Forgetting the last bit. Using only bits[i >> 1] counts the bits of the shifted number and misses odd numbers' last 1.

    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 Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free