338. Counting Bits

Solution

/**
 * @param {number} n
 * @return {number[]}
 */
var countBits = function(n) {
    const res = [0];
    
    let offset = 1;
    for (let i = 1; i <= n; i++) {
        if (offset * 2 === i) {
            offset = i;
        }
        res.push(1 + res[i - offset]);
    }
    
    return res;
};

Complexity

  • Time Complexity: O(N), where N is the size of n.
  • Space Complexity: O(N), where N is the size of res.

All Solutions