EasyNo. 0338

Counting Bits — LeetCode 338 Python Solution

Topics
Bit Manipulation, Dynamic Programming
On study lists
Blind 75, NeetCode 150 and LeetCode 75
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

PythonSolution
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

Related problems
No.ProblemDifficulty
0397Integer ReplacementMedium
0464Can I WinMedium
0473Matchsticks to SquareMedium
0526Beautiful ArrangementMedium
0638Shopping OffersMedium
0698Partition to K Equal Sum SubsetsMedium

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.

Free to download. Check it runs on your machine, then pick a plan.