#338

Counting Bits

Easy
Dynamic ProgrammingBit ManipulationBit ManipulationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n log n)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the relationship between numbers. The number of 1s in the binary representation of a number can be derived from previously computed results, specifically using the formula: ans[i] = ans[i >> 1] + (i & 1). This means we can compute the number of 1s in constant time for each number.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array ans of size n + 1 with all zeros.
  2. 2Step 2: For each integer i from 1 to n, calculate ans[i] using the formula: ans[i] = ans[i >> 1] + (i & 1).
  3. 3Step 3: Return the ans array.
solution.py5 lines
1def countBits(n):
2    ans = [0] * (n + 1)
3    for i in range(1, n + 1):
4        ans[i] = ans[i >> 1] + (i & 1)
5    return ans

Complexity note: The time complexity is O(n) because we iterate through all numbers from 1 to n once, and each operation inside the loop is O(1).

  • 1Understanding how binary representation works is crucial for solving bit manipulation problems.
  • 2Leveraging previously computed results can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.