I was solving this problem https://practice.geeksforgeeks.org/problems/frequency-of-array-elements-1587115620/1 .
I am unable to figure why it is giving runtime error .
Problem Statement:
Given an array A[] of N positive integers which can contain integers from 1 to P where elements can be repeated or can be absent from the array. Your task is to count the frequency of all elements from 1 to N.
Note: The elements greater than N in the array can be ignored for counting.
Constraints:
1 ≤ N ≤ 105
1 ≤ P ≤ 4*104
1 <= A[i] <= P
My Approach:
Since A[i] >= 1 , I stored the counts in negative and at the end just took their absolute value .
using namespace std;
// } Driver Code Ends
class Solution{
public:
//Function to count the frequency of all elements from 1 to N in the array.
void frequencyCount(vector<int>& arr,int N, int P)
{
// code here
for(int i = 0 ;i < N; ++i){
int ele = arr[i];
if(ele > N ){
arr[i] = 0 ;
}
else if(ele < 1){
continue;
}
else{
arr[i] = 0 ;
int next;
while(arr[ele - 1] > 0){
next = arr[ele - 1];
arr[ele - 1] = -1 ;
ele = next ;
}
arr[ele - 1] = arr[ele - 1] - 1;
}
}
for(int &i : arr ){
i = abs(i);
}
}
};
// { Driver Code Starts.
int main()
{
long long t;
//testcases
cin >> t;
while(t--){
int N, P;
//size of array
cin >> N;
vector<int> arr(N);
//adding elements to the vector
for(int i = 0; i < N ; i++){
cin >> arr[i];
}
cin >> P;
Solution ob;
//calling frequncycount() function
ob.frequencyCount(arr, N, P);
//printing array elements
for (int i = 0; i < N ; i++)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends
Error:
On submitting the solution it shows this
Test Cases Passed:
2 / 100020
Input:
5
1 1 1 1 1
1
Your Output:
Abort signal from abort(3) (SIGABRT)
Its Correct output is :
5 0 0 0 0
The problem is my code gives correct output for the above test case.