← All Exercises

Counting Bits with Dynamic Programming

basicjavascript~25min

Background

Popcount tables support bitmap indexes, Hamming distance, and compact cardinality sketches over small ranges.

Problem

Given a non-negative integer n, return an array where entry i is the number of set bits in the binary representation of i, for all i from 0 to n.

Input

A single non-negative integer n no larger than 100000.

Output

An array of length n + 1 containing the set-bit count for each index.

Sample tests

Sample 1

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

Sample 2

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

Sample 3

Input: n = 0
Expected: [0]

Your solution

Learning objective

Derive a DP recurrence from binary structure and fill a table in a single pass.