DSA AnimatorREVISION VIDEOS
← Back to problems
New

Counting Bits — LeetCode 338 video explanation

For every number i from 0 to n, count the 1 bits in i. Return all the counts in an array.

Loading videos…

DSA Animator › DSA Revision › Bit Manipulation › Counting Bits

Key moments in the Counting Bits video

0:05Problem0:12Example0:17Brute force0:25Key idea0:43Dry run1:07Code1:20Takeaway

What you will learn

Remember: i shifted right is i without its last bit. Dynamic programming over smaller numbers. The video solves Counting Bits (LeetCode 338, Easy) with the DP on Bits pattern from the Bit Manipulation topic, and you can replay every step in the interactive Counting Bits animation.

Counting Bits video transcript

Problem

For every number i from 0 to n, count the 1 bits in i. Return all the counts in an array.

Example

For n equal to 5, the answer is 0, 1, 1, 2, 1, 2.

Brute force

Counting the bits of each number separately takes O of n log n. But each count can be built from a smaller number.

Key idea

Shifting i right by one drops its last bit. So i has the same bits as i shifted right, plus its last bit. That gives the rule: bits of i equals bits of i over 2, plus i AND 1. Because i over 2 is smaller, its count is already in the array.

Dry run

bits of 0 is 0. 1 is 1 shifted, which is 0, plus last bit 1, so 1. 2 is 10: half is 1 with count 1, plus last bit 0, so 1. 3 is 11: half is 1, plus last bit 1, so 2. 4 is 100: half is 2 with count 1, so 1. 5 is 101: half is 2, plus 1, so 2.

Code

In code, create an array of size n plus 1. For i from 1 to n, set ans of i to ans of i shifted right by one, plus i AND 1. Return the array, so it's O of n time.

Takeaway

Remember: i shifted right is i without its last bit. Dynamic programming over smaller numbers.

More Bit Manipulation revision videos

← All 185 DSA revision videos