easyArraysPattern: Hashing

Unique Element Count Solution

Problem Statement

Given an array of integers, write a function to count the number of unique elements in the array.

Examples

Example 1:
Input:[1, 2, 3, 2, 1, 4]
Output:4
Explanation: The unique elements in the array are 1, 2, 3, and 4.
Example 2:
Input:[5, 5, 5, 5]
Output:1
Explanation: The only unique element in the array is 5.
Example 3:
Input:[1, 2, 3, 4, 5, 6]
Output:6
Explanation: All elements in the array are unique.

Constraints

  • The input array will not be null or empty
  • The input array will contain only integers
  • The input array can contain duplicates
Time: O(n) Space: O(n)
Use a set data structure to count unique elements, which takes O(n) time and O(n) space.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def count_unique_elements(array):