1

I have tried a problem in leetcode IDE. Got a runtime error on running the below code.

As I am a beginner, I'm not able to debug the error.

class Solution 
    {
       public:
             vector<int> runningSum(vector<int>& nums) {
             vector<int> result;
             int  n=nums.size();
             for(int i=0;i<n;i++)
             {
                int sum=0;
                for(int j=0;j<=i;j++)
                {
                   sum=sum + nums[j];
                }
                result[i]=sum;
                
            }
            return result;
        }
    };
1
  • result is empty. Any indexing into it will be out of bounds and lead to undefined behavior. Commented Jun 3, 2021 at 11:30

1 Answer 1

2

The problem in your solution is that result[i] is not a defined address because result vector is empty, it does not have any size defined.

You can either use result.push_back(sum); or while declaring vector<int> result(n); but not both.

Complete code

class Solution 
    {
       public:
       vector<int> runningSum(vector<int>& nums) {
             int  n=nums.size();
             vector<int> result(n);
             
             for(int i=0;i<n;i++)
             {
                int sum=0;
                for(int j=0;j<=i;j++)
                {
                   sum=sum + nums[j];
                }
                result[i]=sum;
                
            }
            return result;
        }
    };

Unrelated but there is an efficient and shorter way to implement this code. Your code has a time complexity of O(n2) but it can be done in O(n) like below:

class Solution 
    {
       public:
       vector<int> runningSum(vector<int>& nums) {
             int  n=nums.size();
             vector<int> result(n);
             
             result[0] = nums[0];
             for(int i=1;i<n;i++)
             {
                result[i] = result[i-1] + nums[i];
             }
             return result;
        }
    };
Sign up to request clarification or add additional context in comments.

2 Comments

Why cannot we use both push_back as well as vector<int> result(n)? Thanks
@SurbhiJain If u read how vector<int> result (n) works and how push_back() works, u wud get the answer. If u use vector<int> result (n), it initializes the vector result already with n spaces, if u now use push_back, u wud be pushing any new element on nth index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.