Counting bits problem from dyanammic programming

Problem LInk:

I don’t know my below code is giving wrong answer

public:
    vector<int>  countBits(int n) {
        vector<int> dp(n+1);
        dp[0] = 0;
        dp[1]=1;
     for(int i=2; i<=n;i++){
         
        
            dp[i] = i%2+ dp[i/2];
          
        }
        return dp;

}
};

while this one is giving correct answer

public:
    vector<int>  countBits(int n) {
        vector<int> dp(n+1);
        dp[0] = 0;
    
     for(int i=1; i<=n;i++){
         
        
            dp[i] = i%2+ dp[i/2];
          
        }
        return dp;

}
};

Hi, I think your code is getting wrong for case n=0.
Here’s the explanation:
First, let’s see the constraints:
image
So, for n=0 your code will make a vector of size 1

vector<int> dp(n+1);
dp[0] = 0;
dp[1]=1;

But here by doing dp[1]=1 you are assigning value out of the size of the vector, which results in a runtime error on leetcode.

1 Like

thanks :grinning_face_with_smiling_eyes: