Counting Bits — LeetCode 338 Python Solution
- Problem
- #338
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- n = 2
- Output
- [0,1,1]
- Explanation
- 0 --> 0
Python solution
class Solution:
def countBits(self, n: int) -> List[int]:
return [i.bit_count() for i in range(n + 1)]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 338. Counting Bits is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150 and LeetCode 75.
Frequently asked questions
- How hard is LeetCode 338. Counting Bits?
- LeetCode 338. Counting Bits is rated Easy on LeetCode.
- What topics does LeetCode 338. Counting Bits cover?
- LeetCode 338. Counting Bits is tagged Bit Manipulation and Dynamic Programming on LeetCode.