Objective: Given an array of integers, write a program to check if array contains all unique numbers.

Example:

Integer [] arrA = { 1, 2, 3, 6, 4, 9, 8};
Output: Array has all distinct elements
Integer [] arrB = { 1, 2, 3, 6, 4, 9, 8, 2};
Output: Array contains duplicates

Approach:

Brute Force:

Use two nested loops and compare each element with all other elements to validate whether array contains any duplicates.

Time Complexity: O(N^{2})

Better Solution:

Use HashSet:

Create a HashSet from the given array.

Since Set does not contains duplicates, if original array has any duplicates, the size of HashSet will not be equal to the size of array and if size matches then array has all unique elements.

Time Complexity: O(N) , Space Complexity: O(N)

Complete Code:

Output:

Given array has all unique or distinct elements [1, 2, 3, 6, 4, 9
Given array does not contains all unique elements, and contains duplicate elements [1, 2, 3, 6, 4, 9, 8, 2]

__________________________________________________ Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________