0

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

2
  • clearly the error tells integer overflow. read the error carefully. Commented Apr 15, 2022 at 5:01
  • Your question title should be more specific and straight to the problem Commented Apr 15, 2022 at 5:01

1 Answer 1

1

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.

Edit: Now I use Java for problem-solving. So there might be some error in syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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