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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit