Problem Description
Given a non-negative integer n, return an array ans of length n + 1 such that for each index i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
Key Insights
- We can use dynamic programming to build the solution by utilizing the count of bits for smaller numbers.
- The relationship dp[i] = dp[i >> 1] + (i & 1) holds, where i >> 1 gives the count for i divided by 2 (dropping the least significant bit) and (i & 1) checks if the least significant bit is 1.
- This approach computes the result for each number in constant time, resulting in a linear time solution.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(n)
Solution
We use a dynamic programming approach where an array (or list) dp is initialized with size n+1. The key idea is to iterate from 1 to n and for each number, use the formula dp[i] = dp[i >> 1] + (i & 1).
- The expression (i >> 1) effectively divides i by 2, giving the count of 1's for that half number.
- The (i & 1) operation checks if i is odd, adding 1 if true. This method ensures each dp[i] is computed in constant time, leading to an overall O(n) time complexity.