0

"Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays." I was trying to solve this question on Leetcode.

This is the code I wrote:

int findLength(vector<int>& nums1, vector<int>& nums2) {
    int l1=nums1.size()+1;
    int l2= nums2.size()+1;
    int dp[1000][1000]={0};
    for(int i=l1-1; i>=0; i++){
        for(int j=l2-1; j>=0; j++){
            if(nums1.at(i)==nums2.at(j)){
                dp[i][j]=dp[i+1][j+1]+1;
                break;
            }
        }
    }
    int maxm=0;
    for(int i=0; i<l1; i++){
        for(int j=0; j<l2; j++){
            if(dp[i][j]>maxm){
                maxm=dp[i][j];                }
        }
    }
    return maxm;
}

But I got an error I cant understand:

terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 4) >= this->size() (which is 4) Blockquote

Blockquote

  • 1
    Are you sure that in first two for-statements you want i++ and j++? Should be -- on both – Jakub Stasiak Jul 10 '21 at 09:12
  • 1
    `int l1=nums1.size()+1`? Why `+1`? Especially since it means that `int i=l1-1` will put `i` out of bounds. – Some programmer dude Jul 10 '21 at 09:12
  • 1
    Your index `i` has a starting value of `nums1.size()` but you have `nums1.at(i)`. So you're immediately out-of-bounds. – G.M. Jul 10 '21 at 09:12
  • 3
    And my usual rant: Don't use so-called "competition" or "online judge" sites as a learning or teaching resource, because that's not what they are (unless you want to learn so bad habits that it can make you virtually unemployable). Get [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and take classes, that's how you learn programming and C++. – Some programmer dude Jul 10 '21 at 09:14
  • `int dp[1000][1000]={0};` This statement allocates 4 MB on the stack, which is very limited (1 MB on Windows, 8 MB on Linux). Use dynamic allocation, like with `std::vector`. – prapin Jul 10 '21 at 09:25
  • Thanks for the suggestions. I made some changes and now the program doesn't have any error but it still wont pass most of the test cases :( – Vivek Anand Jul 10 '21 at 09:32

0 Answers0