You are given a list of N integers and a value K. Print 1 if K exists in the given list of N integers, otherwise print β1.
Input:
- First-line will contain two numbers N and K.
- Next line contains N space-separated numbers.
Output:
*Print the answer in a new line.
my code
#include <stdio.h>
int main()
{
int n,k,i,a[100000],count=0;
scanf("%d %d\n",&n,&k);
for(i=0;i<n;i++)
{
scanf("%d ",&a[i]);
if(a[i] == k)
{
count = count + 1;
}
}
if(count == 1)
{
printf("1");
}
else
{
printf("-1");
}
return 0;
}
Problem Link
My Solution Link
Make 2 changes to your code
First change a[100000] to a[100001]
Next change the if else logic you used at last.Change if(count==1) to if(count>=1)
After doing these changes your code should work fine.
1 Like
Thanks a ton
But please tell how these changes helped?
In your if else condition if a number is present more than once you were executing the else condition and so -1 was getting printed as you only checked if count=1 but count can be more than 1 also when an element is present more than once. And for that array size thing itβs not necessary for your approach but itβs necessary if you use a hashing bashed approach where you store the frequency of each element.