Here is my code for a problem in CSES problem set "Distinct Numbers". The problem basically inputs an integer (i
) specifying the no. of elements and and an array of length equal i
. We basically have to find the distinct no. of elements in that array.
#include <iostream>
using namespace std;
bool check(unsigned long long int val, unsigned long long int arr[], unsigned long long int range) {
unsigned long long int i;
bool return_val = true;
for (i=0; i<range; i++) {
if (arr[i] == val) {
return_val = false;
}
}
return return_val;
}
int main()
{
//cout << "DEBUG-1" << endl;
unsigned long long int i;
cin >> i;
unsigned long long int in_array[i];
unsigned long long int j;
for (j=0; j<i; j++) {
cin >> in_array[j];
}
unsigned long long int sort_array[i];
unsigned long int long sort_array_index = 0;
for (j=0; j<i; j++) {
if(check(in_array[j], sort_array, sort_array_index)) {
sort_array[sort_array_index] = in_array[j];
sort_array_index++;
}
}
cout << sort_array_index;
}
When the input is not huge and is limited to 2 digit inputs, the code works fine.
The problem I'm facing is that when the input is 200000, my code breaks and shows there is no output as the time limit for compilation exceeds 1 second. Here is my issue: There's a test case on the site in which i=200000, and the array consists of all 1's. The obvious answer is 1 and my output is also 1. But, when i=200000, and all values are distinct the above issue occurs and the input displayed on the test is (empty).
Even when I include the first cout << "DEBUG-1" << endl;
line (commented out), it is not seen in the output, whereas it is even before the first input line. It's like the program just rejects the input on seeing it. What I'm not able to understand that I wrote a similar program for an earlier problem and it worked fine on big inputs. Please tell me what is going wrong and include suggestions to write better code as well.