In a party everyone is in couple except one. People who are in couple have same numbers. Find out the person who is not in couple.
Input:
The first line contains an integer \$T\$ denoting the total number of test cases. In each test cases, the first line contains an integer \$N\$ denoting the size of array. The second line contains \$N\$ space-separated integers \$A_1, A_2, \ldots, A_N\$ denoting the elements of the array. (\$N\$ is always odd)
Output:
In each seperate line print number of the person not in couple.
Constraints:
\$ 1 \leq T \leq 30\$
\$ 1 \leq N \leq 500\$
\$ 1 \leq A[i] \leq 500\$
\$ N \% 2 = 1\$
Example:
Input:
1 5 1 2 3 2 1
Output:
3
My approach:
/*package whatever //do not write package name here */
import java.util.Scanner;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
class GFG {
private static int getAloneNum (int[] arr) {
List<Integer> alone = new ArrayList<>();
for (Integer elem : arr) {
if (!(alone.contains(elem))) {
alone.add(elem);
}
else {
alone.remove(alone.indexOf(elem));
}
}
return alone.get(0);
}
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int numTests = sc.nextInt();
for (int i = 0; i < numTests; i++) {
int size = sc.nextInt();
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = sc.nextInt();
}
System.out.println(getAloneNum(arr));
}
}
}
I have the following questions with regards to the above code:
How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?
Is my code very redundant?
LinkedList
should be faster thanArrayList
for adding and removing items \$\endgroup\$