> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Counting Bits Python Solution with Tests

> Tested Python solution for LeetCode 338 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 338, Easy. Topics: Dynamic Programming, Bit Manipulation. [View on LeetCode](https://leetcode.com/problems/counting-bits/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 338   # by problem number
lcpy gen -s counting_bits   # by problem name
```

## Problem

Given an integer `n`, return *an array* `ans` *of length* `n + 1` *such that for each* `i` *(0 \<= i \<= n),* `ans[i]` *is the **number of*** `1`***'s** in the binary representation of* `i`.

### Examples

```
Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
```

```
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
```

### Constraints

* 0 \<= n \<= 10^5

**Follow up:**

* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/counting_bits/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/counting_bits/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    def count_bits(self, n: int) -> list[int]:
        """
        Optimized version with better variable naming and comments.

        Time: O(n)
        Space: O(1) excluding output array
        """
        if n == 0:
            return [0]

        bits_count = [0] * (n + 1)

        for num in range(1, n + 1):
            # For any number, the count of 1s equals:
            # count of 1s in (num >> 1) + whether the last bit is 1
            bits_count[num] = bits_count[num >> 1] + (num & 1)

        return bits_count
```

## Complexity

| Time | Space |
| ---- | ----- |
| -    | -     |

## Tags

[Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
