Be the first user to complete this post

  • 0
Add to List
Beginner

356. Check if array contains all unique or distinct numbers

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(N2)

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)

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]