1. Individual Popcount Simulation
Intuition
Allocate array ans of size n + 1. For each index i from 0 to n, run Brian Kernighan's bit-clearing loop on i to compute its set bit count.
When to apply: Baseline comparison without dynamic programming.
Algorithm
- Step 1: Allocate ans array of size n + 1.
- Step 2: Loop i from 0 to n.
- Step 3: Count set bits of i using temp &= (temp - 1).
- Step 4: ans[i] = count.
- Step 5: Return ans.
#include <iostream>#include <vector> using namespace std; vector<int> countBitsBrute(int n) { vector<int> ans(n + 1, 0); for (int i = 0; i <= n; ++i) { int temp = i; int count = 0; while (temp > 0) { temp &= (temp - 1); count++; } ans[i] = count; } return ans;} int main() { auto res = countBitsBrute(5); cout << "Brute (5): "; for (int v : res) cout << v << " "; cout << endl; // 0 1 1 2 1 2 return 0;}Time & Space Complexity
- Time complexity:
O(n log n) - Space complexity:
O(1) auxiliary space