Naina Garg
Naina Garg

Reputation: 25

Why is it showing Run-time error in 3Sum problem on LeetCode?

I was solving this 3Sum problem on leetcode. The question states that: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

This solution which I code is:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        
        
        vector<vector<int>> arr;
         
        sort(nums.begin(),nums.end());
        for(int i=0;i<(nums.size())-2;i++)
        {
            if(i==0 || (i>0 && nums[i]!=nums[i-1]))
            {
                int low,high,sum;
                low=i+1;
                high=nums.size()-1;
                sum=0-nums[i];
                while(low<high)
                {
                    int a=nums[low]+nums[high];
                    if(a== sum)
                    {
                        vector<int> p;
                        p.push_back(nums[i]);
                        p.push_back(nums[low]);
                        p.push_back(nums[high]);
                        arr.push_back(p);
                        while(low<high && nums[low]==nums[low+1])
                            low++;
                        while(low<high && nums[high]==nums[high-1])
                            high--;
                        low++;
                        high--;
                    }
                    else if(a>sum)
                        high--;
                    else
                        low++;
                }
            }            
        }
        return arr;
    }};

But it was showing run time error for the base condition when size of the given vector is less than 3. Also, the for loop was designed in such a way that it won't run for the base condition i.e. vector size less than 3.

Can anyone tell why is it showing such an error?

Upvotes: 0

Views: 160

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

nums.size() returns an unsigned integer, so (nums.size())-2 will be some large value due to wraparounding when nums.size() is less than 2.

You should use static_cast<int>(nums.size())-2 instead of (nums.size())-2 and static_cast<int>(nums.size())-1 instead of nums.size()-1.

Upvotes: 0

Related Questions