Counting Bits

Easy · Bit Manipulation · Dynamic Programming · Bit Manipulation

Problem

Given an integer n, return an array of length n + 1 where position i holds the number of 1 bits in i.

Examples

Input: n = 2
Output: [0,1,1]

0, 1, 10 in binary.

Input: n = 5
Output: [0,1,1,2,1,2]

Constraints

Approaches

Follow-up

Counting bits for each number separately takes O(n log n). Can you produce the answer in a single O(n) pass without using a built-in popcount?

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…