Lesson guide
What this Python exercise practices
Count unique elements is a beginner practice lesson that focuses on dsa, problem patterns, edge cases. It is designed to be solved in about 6 minutes with examples, starter code, and test feedback.
Prerequisites
- Python functions
- Loops
- Lists
- Basic edge cases
Difficulty and time
- Level
- Beginner
- Estimated time
- 6 minutes
Related public exercises
Summary
Return the number of distinct elements in a list using hashing (sets).
Problem statement
You are given a list of elements (typically integers). Implement a function count_unique(nums) that returns the number of unique elements in the list. Use a set (hashing) to achieve O(n) time on average and O(n) extra space. The function should handle an empty list and lists with repeated values.
Task
Given a list, compute how many unique values it contains in O(n) time using a set.
Examples
Basic example
Input
count_unique([1, 2, 2, 3])
Output
3
Explanation
The unique elements are 1, 2, and 3, so the function returns 3.
Input format
A single list of elements (e.g., integers), for example: [1, 2, 2, 3]
Output format
An integer representing the number of unique elements.
Constraints
0 <= len(nums) <= 10^5. Elements are hashable (integers in typical tests). Aim for O(n) time and O(n) space.
Samples
Sample input 0
[5, 5, 6, 7, 7, 7]
Sample output 0
3
Explanation 0
Unique elements are 5, 6, and 7.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.