problem link
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- > 0){
int a=sc.nextInt();
int n=2*a;
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int count=0;
for(int j=0;j<n-1;j++){
for(int k=j+1;k<n;k++){
if(arr[j]==arr[k]){
count++;
}
}
}
if(count>2){
System.out.println("No");
}
else{
System.out.println("Yes");
}
}
}
}
I would love to know what logical mistake i am making!
Well there are two small mistakes in your code.
Firstly according to your logic you are checking for same elements in the entire array. So every time any two elements are same you are updating the count but that should not be the case as per the problem.
You should be looking for any one element in the array which is repeated 3 times or more. So basically if there are 3 elements same you know that it won’t be possible for them to be distributed distinctly. So you need to find if every element has two more copies of it in the array as a minimum requirement. For that you should set count to 0 before your k loop so it resets to 0 for every element. You can use a break statement too in the loop so once you find a count that is >=2 you get out of the loop and stop iterating.
Another thing is you should be checking for count>=2 not count>2. Because if the count is 2 it means you found 2 more duplicate elements in the array which means there is a total of 3 elements that are same including the one you found the count for.
Here's the code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- > 0){
int a=sc.nextInt();
int n=2*a;
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int count=0;
for(int j=0;j<n-1;j++){
for(int k=j+1;k<n;k++){
if(arr[j]==arr[k]){
count++;
}
}
if(count>=2)
break;
count = 0;
}
if(count>=2){
System.out.println("No");
}
else{
System.out.println("Yes");
}
}
}
}
Hopefully that clears your doubt!