Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Easy Bit Manipulation High frequency Solution Available Practice Mode

Counting Bits LeetCode Solution

Tags: #DP #Bit Manipulation

Approach Summary

dp[i] = dp[i >> 1] + (i & 1). The number of 1-bits in i is same as i/2 plus the last bit.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Bit Manipulation Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Bit Manipulation pattern.

Framework: Bit Manipulation • Interview Prep: Tested at FAANG • Explore all Bit Manipulation problems & invariants →

How to Recognize This Pattern

  • Count set bits for all numbers 0..n

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)

Tags

DP Bit Manipulation

Frequently Asked Questions

What is the optimal time and space complexity for Counting Bits?
The optimal solution for Counting Bits achieves O(n) runtime complexity and requires O(n) auxiliary space. Time complexity is O(n) because we compute each entry dp[i] in O(1) time using a single bit-shift, bitwise AND, and addition. Auxiliary space complexity is O(1) beyond the O(n) space required to store the returned array.
How do I identify that Counting Bits requires the Bit Manipulation pattern?
In technical interviews, look for key problem signals: Count set bits for all numbers 0..n. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Bit Manipulation strategy.
What critical edge cases must be handled in Counting Bits?
Essential edge cases to verify include: n = 0 (returns [0]); n = 1 (returns [0, 1]); Powers of two (e.g. 2, 4, 8, 16; each has exactly one 1-bit and resets pattern); Large values of n up to 10^5 (linear pass executes seamlessly under 5ms). Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Counting Bits?
Counting Bits is a Easy-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Google, Facebook.
Buy me a coffee
Daily Practice
0/0