← Home

338. Counting Bits

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
bit manipulationC++Markdown
338

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 338. Counting Bits, the solution in this repository is mainly a bit manipulation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: bit manipulation.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are countBits, ret.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: Space complexity should be O(n).

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
03
04Example 1:
05
06Input: 2
07Output: [0,1,1]
08Example 2:
09
10Input: 5
11Output: [0,1,1,2,1,2]
12Follow up:
13
14It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
15Space complexity should be O(n).
16Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
17**/
18
19//Your runtime beats 60.09 % of cpp submissions.
20class Solution {
21public:
22    vector<int> countBits(int num) {
23        vector<int> ans;
24        for(int i=0;i<=num;i++){
25            int count = 0;
26            int j = i;
27            while(j!=0){
28                count+=j%2;
29                j/=2;
30            }
31            ans.push_back(count);
32        }
33        return ans;
34    }
35};
36
37//Your runtime beats 43.45 % of cpp submissions.
38class Solution {
39public:
40    vector<int> countBits(int num) {
41        vector<int> ans;
42        for(int i=0;i<=num;i++){
43            ans.push_back(__builtin_popcount(i));
44        }
45        return ans;
46    }
47};
48
49//from hint, suboptimal
50//Runtime: 8 ms, faster than 99.05% of C++ online submissions for Counting Bits.
51//Memory Usage: 7.8 MB, less than 100.00% of C++ online submissions for Counting Bits.
52class Solution {
53public:
54    vector<int> countBits(int num) {
55        vector<int> ans(num+1, 0);
56        
57        for(int i = 1; i < num+1; i++){
58            ans[i] = ans[i/2] + i%2;
59        }
60        
61        return ans;
62    }
63};
64
65//Your runtime beats 97.98 % of cpp submissions.
66class Solution {
67public:
68    vector<int> countBits(int num) {
69        vector<int> ret(num+1, 0);
70        for (int i = 1; i <= num; ++i)
71            ret[i] = ret[i&(i-1)] + 1; //by @fengcc
72            // ret[i] = ret[i/2] + i % 2; //by @sijiec
73        return ret;
74    }
75};
76
77/**
78by @fengcc
79i&(i-1) drops the lowest set bit. For example: i = 14, its binary representation is 1110, so i-1 is 1101, i&(i-1) = 1100, the number of "1" in its binary representation decrease one, so ret[i] = ret[i&(i-1)] + 1.
80**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
Space complexity should be O(n).
Auxiliary state plus the answer structure where the problem requires one.