Bit manipulation & mathLeetCode 338

Lesson 62 of 76

Counting Bits

For every i from 0 to n, return how many 1 bits i has.

Watch on YouTube

Lesson notes

Try it before you watch

Restate the problem in your own words, list the edge cases, and sketch a solution with its running time. Then play the video and compare.

Reveal the key idea

Reuse earlier answers: bits(i) = bits(i >> 1) + (i & 1).

Pattern: Bit manipulation & math. Use XOR, AND and shifts to work on the binary representation directly.

Complexity

Cost of the standard optimal approach for Counting Bits
Measure Bound
Time O(n)
Extra space O(n) for the output

Walkthroughs often start from a simpler approach first; aim to reach these bounds. New to Big-O? Read understanding algorithmic complexity.