easyArraysPattern: Hashing

Count Unique Elements Solution

Problem Statement

You are given an array of integers `nums` and need to implement a function that returns the count of unique elements in the array.

Examples

Example 1:
Input:[1, 2, 2, 3, 4, 4, 5]
Output:5
Explanation: Unique elements are 1, 2, 3, 4, 5. So the count is 5.
Example 2:
Input:[1, 1, 1, 1, 1]
Output:1
Explanation: Only one unique element, which is 1.

Constraints

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • The array may contain duplicate elements
  • The array may be empty
  • The function should return the count of unique elements
Time: O(n) Space: O(n)
A more optimal approach is to utilize a data structure like a hash set, which allows for constant time complexity lookups and insertions. By iterating through the array and adding each element to the set, we can easily count the unique elements in linear time complexity. This approach provides a significant performance improvement over the brute force method.

Run, Test & Submit Code

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

Solve on Interactive Workspace

Tested Solutions

import sys input = sys.stdin.readline nums = list(map(int, input().split())) unique_count = len(set(nums)) print(unique_count)