Counting Bits - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

  • We want to compute, for every integer i in the range [0, n], the number of 1 bits (set bits) in the binary representation of i. We store each result in an array onesCount where onesCount[i] = β€œnumber of 1’s in the binary representation of i”.
  • Key idea β€” reuse work by removing the last bit:
    For any integer currentNum, its binary form can be split into:

    (binary prefix) Β· (last bit)

    The number of 1’s in the binary representation of currentNum equals the number of 1’s in the binary prefix plus the value of the last bit. Since we fill onesCount in increasing order, the count of 1’s in the binary prefix must already be stored in the DP array. The index for this prefix is the decimal value of the prefix itself, which we call shiftedNum, computed as currentNum >> 1. The last bit (denoted lastBit) is obtained using currentNum & 1. Therefore, the count of 1’s in currentNum is simply:

    onesCount[currentNum] = onesCount[shiftedNum] + lastBit.
  • Dynamic programming relation:
    We build onesCount in increasing order so that onesCount[shiftedNum] is always known before computing onesCount[currentNum].
    • shiftedNum = currentNum >> 1
    • lastBit = currentNum & 1
    • onesCount[currentNum] = onesCount[shiftedNum] + lastBit
  • Building the table:
    • Initialize onesCount with n + 1 entries.
    • Set onesCount[0] = 0.
    • For each currentNum from 1 to n, apply the formula above.

Time Complexity

We iterate once from 1 to n, and each step performs only constant-time operations using the dynamic programming relation. Therefore, the overall time complexity of the algorithm is O(n).

Space Complexity

O(n) β€” We store one computed value for each integer from 0 to n in the output array.

Visucodize editorial solution titled JS Solution for LeetCode's Counting Bits coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/counting-bits.