Top 150 InterviewEasy

Counting Bits

Detailed guide and Python implementation for the 'Counting Bits' problem.

Problem Statement

Easy

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.

Write a function countBits(n: int) -> List[int].

Constraints
  • 0 <= n <= 10^5

Examples

Example 1
Input
n = 2
Output
[0,1,1]
Explanation

0 -> 0; 1 -> 1; 2 -> 10.

Example 2
Input
n = 5
Output
[0,1,1,2,1,2]
Explanation

0 -> 0; 1 -> 1; 2 -> 1; 3 -> 2; 4 -> 1; 5 -> 2.

Need a Hint?
Consider using Bit Manipulation-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.