EasyNo. 0338
Counting Bits — LeetCode 338 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation, Dynamic Programming
- On study lists
- Blind 75, NeetCode 150 and LeetCode 75
- 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
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
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
| No. | Problem | Difficulty |
|---|---|---|
| 0397 | Integer Replacement | Medium |
| 0464 | Can I Win | Medium |
| 0473 | Matchsticks to Square | Medium |
| 0526 | Beautiful Arrangement | Medium |
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
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.