Counting Bits — LeetCode 338 Python Solution

EasyBit ManipulationDynamic Programming
Problem
#338
Reading time
2 min

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

Python
class Solution:
    def countBits(self, n: int) -> List[int]:
        return [i.bit_count() for i in range(n + 1)]

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview