EASY NC#146 Blind #13 Bit Manipulation / Dynamic Programming
338. Counting Bits
๐ Problem
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขArray DP table updates
- โขState transition thinking
- โขBase case initialization
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Dynamic Programming reasoning pattern
๐ก Approach
- โ Use pattern: bits[i] = bits[i >> 1] + (i & 1)
- โ Right shift i by 1 gives i/2, which has same bit pattern except last bit
- โ Add 1 if last bit is 1 (i & 1 == 1), else add 0
- โ Time: O(n), Space: O(n)
- โ in popcount
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse pattern: bits[i] = bits[i >> 1] + (i & 1)
- โขRight shift i by 1 gives i/2, which has same bit pattern except last bit
- โขAdd 1 if last bit is 1 (i & 1 == 1), else add 0
Common Pitfalls
- โขTime: O(n), Space: O(n)
- โขin popcount
๐งช Test Cases
Test Case 1
Not run Input:
countBits(2); Expected:
[0, 1, 1] Test Case 2
Not run Input:
countBits(5); Expected:
[0, 1, 1, 2, 1, 2] Test Case 3
Not run Input:
countBits(n: number); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output