J – Print unique elements of array

Print unique elements of the array in the same order as they appear in the input.
Note: Do not use any inbuilt functions/libraries for your main logic.

Input Format

First line of input contains a single integer N – the size of array and second line contains array elements.

Constraints

1 <= N <= 100
0 <= ar[i] <= 109

Output Format

Print unique elements of the array.

InputcopyOutputcopy
7
5 4 10 9 21 4 10
5 9 21

Explanation 0

Self Explanatory.

Solutions:

import java.util.Scanner;

public class UniqueElements {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int[] arr = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = scanner.nextInt();
        }
        printUniqueElements(arr);
        scanner.close();
    }

    public static void printUniqueElements(int[] arr) {
        boolean[] visited = new boolean[arr.length];
        for (int i = 0; i < arr.length; i++) {
            if (!visited[i]) {
                boolean isUnique = true;
                for (int j = i + 1; j < arr.length; j++) {
                    if (arr[i] == arr[j]) {
                        isUnique = false;
                        visited[j] = true;
                    }
                }
                if (isUnique) {
                    System.out.print(arr[i] + " ");
                }
            }
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top