easyArraysPattern: Hashing
Determine Unique Element Count Solution
Problem Statement
You are given an array of integers `nums`. Your task is to determine the total number of distinct (unique) elements present in the array.
Examples
Example 1:
Input:nums = [1, 2, 2, 3, 1]
Output:undefined
Explanation: The distinct elements in the array are 1, 2, and 3.
Example 2:
Input:nums = [7, 7, 7, 7]
Output:undefined
Explanation: The only distinct element in the array is 7.
Example 3:
Input:nums = []
Output:undefined
Explanation: An empty array contains no elements, thus no distinct elements.
Constraints
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- Expected time complexity: O(N)
- Expected space complexity: O(N)
Time: O(N) Space: O(N)
The most efficient way is to utilize a hash set (or 'Set' data structure). Iterate through the array once, adding each element to the set. Since sets only store unique values, the final size of the set will directly represent the total number of distinct elements, achieving O(N) time complexity on average.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
def solve():
# Read a single line of space-separated integers
line = sys.stdin.readline().strip()
if not line:
# Handle empty input case if necessary, e.g., print 0
print(0)
return
nums = list(map(int, line.split()))
unique_elements = set(nums)
print(len(unique_elements))
if __name__ == '__main__':
solve()