Home > Software engineering >  How Can I fix the following Error in leetcode?
How Can I fix the following Error in leetcode?

Time:04-20

For the question: Given an array of integers nums, return the number of good pairs.

A pair (i, j) is called good if nums[i] == nums[j] and i < j.

I wrote the following code:

 int numIdenticalPairs(vector<int>& nums) {
   
 int count[102];

for (int num : nums) {
  count[num]  ;
}

int totalCount = 0;

// Calculate total number of pairs possible
for (int i : count) {
  totalCount  = ((i) * (i-1))/2;
}

return totalCount;

}

I am getting following error help me fix it:

Line 21: Char 26: runtime error: signed integer overflow: -1844207608 * -1844207609 cannot be represented in type 'int' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:30:26

CodePudding user response:

For this type of question, you need to give the constraints as well. Still, I'm trying from my experience.

In C , the array you declare in the function/method without malloc or new, goes to in stack and keeps garbage values if you don't put anything. So, you need to initialize it first. Do this:

memset(count, 0, sizeof(count));

As I am not seeing any constraints here, if values of count[] is even near 10^5, you will get integer overflow in multiplication of i x (i-1) as well. So try this:

for (int i : count) {
    totalCount  = ((i) * ((long long)(i-1)))/2;
}

Hope, these will solve the problem.

  • Related