Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Count unique elementsE02. Remove duplicates from a listE03. Check if an array contains duplicatesE

Problem No 1

Count unique elements

Easy

6 minute session

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.

Code editor
Loading editor…

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.

03:42 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.