Back to Practice Dashboard
Top 150 InterviewEasy

Counting Bits

Learn how to solve the 'Counting Bits' problem. This detailed resource details brute force and optimized approaches.

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?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor