Skip to main content
2 of 2
mathjax, example formatted as fixed-width text
Vogel612
  • 25.3k
  • 7
  • 58
  • 141

Alone in a Couple implementation in Java

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:

  1. How can I further improve my approach?

  2. Is there a better way to solve this question?

  3. Are there any grave code violations that I have committed?

  4. Can space and time complexity be further improved?

  5. Is my code very redundant?

Reference